您的位置:首页 > Web前端 > JavaScript

js的36个设计模式:前奏

2016-12-12 16:37 211 查看
先是一些js面向对象的基础,后面的模式都会涉及到这些知识点。

构造函数,原型对象

var Fn = function(f){
//var定义私有方法、属性
var num = 1;
//this定义公有方法
this.getF = function(){
//...
}
//构造器,就是实例对象时执行。。
this.getF();
};

给构造函数(类)添加方法:

//添加私有方法,属性
Fn.count = 1;
//添加私有方法,属性
Fn.prototype.counta = 2;

构造函数在实例化的时候,会给对象添加一个prototype原型对象,指向构造函数的属性,方法。并且会创建一个constructor属性,指向拥有整个原型对象的构造函数或对象。


闭包

从一个构造函数里返回一个构造函数生成的对象。。

var Book = (function(){
var a = 0;
function some(){};
function _book(a,b){
this.a = a;
this.b = b;
this.c = function(){
console.log(this.a);
}
this.c();
};
_book.prototype.d = 5;
return _book;
})();
var fn = new Book(1,2);


创建对象的安全模式

用instanceof判断实例化对象时,作用域是否当前构造函数。

var Book = function(a,b){
//如果实例化时,没有写new Book,那么this会指向window作用域
console.log(this);
if(!(this instanceof Book)){
return new Book(a,b);
}else{
this.a = a;
this.b = b;
}
}
//把var book = new Book();写成var book = Book();
var b = Book(1,2);


console.log(this)会执行两次,第一次输出的是window。

继承

1.类式继承

//声明父类
var cat = function(){
this.foot = 4;
};
//父类的方法
cat.prototype.getFoot = function(){
console.log(this.foot);
};
//声明子类
var bigCat = function(){
this.eye = 0;
};
//继承父类,把父类的实例赋值给子类的原型
bigCat.prototype = new cat();
var f = new bigCat();
f.getFoot();


类式继承的缺点,当一个子类实例对象修改从父类继承来的公有属性时,其他子类就会被影响

var fn = function(){
this.a = [1,2,3];
};
var fs = function(){};
fs.prototype = new fn();
var a = new fs();
var b = new fs();
console.log(a.a);//[1,2,3]
a.a.push(4);
console.log(b.a);//[1,2,3,4]


2.构造函数式继承

通过call方法,让构造函数a在b里执行一遍,不过这个办法只能继承构造函数内的方法和属性,不能继承原型prototype的属性!

var a = function(id){
this.id = id;
};
var b = function(id){
a.call(this,id);
};


3.组合继承

同时用类式继承去继承父类的原型,构造函数式继承去继承父类的构造方法

var a = function(){
this.id = 1;
};
a.prototype.name = function(){
console
4000
.log(123);
};
var b = function(){
a.call(this,null);
};
b.prototype = new a();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息