js面向对象
构造函数与原型
工厂模式
function createObject(name,age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.run = function(){
return "xxx";
};
return obj;
}
构造与原型组合
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
constructor : 'Person', //手动添加
sayName : function(){
alert(this.name);
}
}
动态原型模式
function Person(name,age){
this.name = name;
this.age = age;
if (typeof this.sayName != "function"){
Person.Prototype.sayName = function(){
alert(this.name);
}
}
}
寄生构造函数
结合工厂模式和构造函数
function Person(name,age,job){
var o = new Object();
o.name = name;
o.age = age;
o.sayName = function(){
alert(this.name);
};
return o;
}
继承
原型链继承
function SuperType(){}
function SubType(){}
SubType.prototype = new SuperType();
借用构造函数/对象冒充继承
解决传参和原型中的引用问题
function SuperType(a){
this.a = a;
}
function SubType(a){
SuperType.call(this,a);
}
无法实现函数复用。只能继承构造里的信息,无法继承原型。
组合模式
原型+借用
function SuperType(a){
this.a = a;
}
SuperType.prototype.sayA = function(){
alert(this.a);
}
function SubType(a){
SuperType.call(this,a);
}
SubType.prototype = new SuperType();
这样构造和原型都继承了。
原型式继承
function obj(o){ //临时中转函数
function F(){};
F.prototype = o;
return new F();
}
var father = {};
var son = obj(father);
但father中的引用类型会被共享。
寄生式继承
function obj(o){ //临时中转函数
function F(){};
F.prototype = o;
return new F();
}
function create(o){ //寄生函数
var f = obj(o);
//对f扩展
return f;
}
同样也会共享引用。
寄生组合式继承
组合继承调用了两次 new SuperType()
function obj(o){ //临时中转函数
function F(){};
F.prototype = o;
return new F();
}
function create(father,son){ //寄生函数
var f = obj(father.prototype); //创建超类型原型的一个副本
f.constructor = son; //调整原型构造指针
son.prototype = f; //将新创建的对象赋值给子类型原型
}
function SuperType(a){
this.a = a;
}
SuperType.prototype.sayA = function(){
alert(this.a);
}
function SubType(a){
SuperType.call(this,a);
}
create(SuperType,SubType); //传入构造函数名