// 1. 对象冒充继承
function Person(strName){
// private fields
var name = strName;
// public methods
this.getName = function(){
return name;
};
}
function Student(strName,strSchool){
// 定义父类的属性及方法
this.parent = Person;
this.parent(strName);
delete this.parent; // 删除临时变量 parent
// 定义新属性及方法
// private fields
var school = strSchool;
// public methods
this.getSchool = function(){
return school;
};
}
// 2. Funtion 对象的 call(..) 或 apply(..) 继承
// call 和 apply 的区别在于:
// call 的第二个参数为可变参数;
// apply 的第二个参数为 Array;
function Animal(strName,intAge){
// private fields
var name = strName;
var age = intAge;
// public methods
this.getName = function(){
return name;
};
this.getAge = function(){
return age;
};
}
function Cat(strName,intAge,strColor){
// 定义父类的属性及方法
Animal.call(this,strName,intAge);
// Animal.apply(this,new Array(strName,intAge));
// 定义新属性及方法
// private fields
var color = strColor;
// public methods
this.getInfo = function(){
return "name:" + this.getName() + "\n"
+ "age:" + this.getAge() + "\n"
+ "color:" + color;
};
}
// 3. prototype 继承
// prototype 声明的属性及方法被所有对象共享
// prototype 只有在读属性的时候会用到
Function.prototype.extend = function(superClass){
// 此处的 F 是为了避免子类访问父类中的属性 this.xxx
function F(){};
F.prototype = superClass.prototype;
// 父类构造函数
this.superConstructor = superClass;
this.superClass = superClass.prototype;
this.prototype = new F();
this.prototype.constructor = this;
};
Function.prototype.mixin = function(props){
for (var p in props){
this.prototype[p] = props[p];
}
};
function Box(){}
Box.prototype = {
getText : function(){
return this.text;
},
setText : function(text){
this.text = text;
}
};
function CheckBox(){}
CheckBox.extend(Box);
CheckBox.mixin({
isChecked : function(){
return this.checked;
},
setChecked : function(checked){
this.checked = checked;
}
});
9. call , apply & bind
复制代码 代码如下: