原型链 利用原型让一个引用类型继承另外一个引用类型的属性和方法
构造函数,原型,实例之间的关系:每个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function() {
return this.property;
}
function subType() {
this.property = false;
}
//继承了SuperType
subType.prototype = new SuperType();
subType.prototype.getSubValue = function (){
return this.property;
}
var instance = new subType();
console.log(instance.getSuperValue());//true
借用构造函数
在子类型创建的内部调用超类构造函数,通过使用call()和apply()方法可以在新创建的对象上执行构造函数
function Color() {
this.colors = ["red","blue","green"];
}
function type() {
Color.call(this);//继承了Color
}
var instance1 = new type();
instance1.colors.push("black");
console.log(instance1.colors);//"red","blue","green","black"
var instance2 = new type();
console.log(instance2.colors);//"red","blue","green"
上面两种技术组合实现继承
function SuperType(name) {
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
}
function SubType(name, age) {
SuperType.call(this,name);//继承属性
this.age = age;
}
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function() {
console.log(this.age);
}
var instance1 = new SubType("EvanChen",18);
instance1.colors.push("black");
console.log(instance1.colors);//"red","blue","green","black"
instance1.sayName();//"EvanChen"
instance1.sayAge();//18
var instance2 = new SubType("EvanChen666",20);
console.log(instance2.colors);//"red","blue","green"
instance2.sayName();//"EvanChen666"
instance2.sayAge();//20
原型式继承
借助原型可以基于已有的对象创建对象,同时还不必须因此创建自定义的类型
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
var person = {
name:"TIKME",
list:["aa","bb","cc"]
};
var str = object(person);
str.list.push("dd");
var res = object(person);
res.list.push("ee");
console.log(person.list);//["aa", "bb", "cc", "dd", "ee"]
寄生式继承
创建一个仅用于封装继承过程的函数,该函数在内部以某种方式来增强对象,最后再像真正是它做了所有工作一样返回对象
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
function createAnother(original) {
var clone = object(original);
clone.sayHi = function () {
console.log('hi')
};
return clone;
}
var person2 = {
name:"TIKME",
list:["AA","BB","CC"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi();///"hi"
console.log(person2)