一、JavaScript的继承主要使用原型链实现
function Person(name){
this.name = name;
}
function Police(cardNo){
this.cardNo = cardNo;
}
Police.prototype = new Person('Tom');
var police = new Police(1234);
二、借用构造函数
function Person(name){
this.name = name;
};
function Police(name, cardNo){
Person.call(this, name);
this.cardNo = cardNo;
}
var police = new Police('Tom', 1234);
console.log(police.name);
console.log(police.cardNo);
三、组合继承
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
function Police(name, cardNo){
Person.call(this, name);
this.cardNo = cardNo;
}
Police.prototype = new Person('Tom');
var police = new Police('Jerry', 3456);
console.log(police.name);
console.log(police.cardNo);
//其实执行了两次超类型的构造函数,因此,police对象本身有一个name属性,而其指向的原型对象中,也有一个name属性,只是本身的属性屏蔽了原型对象中的属性
四、原型式继承,即返回一个以给定对象为原型的空对象
function Person(o){
function F(){};
F.prototype = o;
return new F();
}
//该方式已经规范化 Object.create(o1, o2);
var person = {
name : 'jerry',
age : 12
}
var extObj = {
cardNo : {
value : 122,
Writable : true
}
}
var newObject = Object.create(person, extObj);
console.log(newObject.name);
console.log(newObject.age);
console.log(newObject.cardNo);
五、寄生式继承,没有构造函数,只是在原型式继承的方式上,增强空对象。
function object(o){
function F(){};
F.prototype = o;
return new F();
}
function createAnother(extO){
var newO = object(extO);
newO.sayHi = function(){
console.log('Hi');
};
return newO;
}
var aObj = {
name : 'Jerry',
age : 12
};
var anotherNewO = createAnother(aObj);
anotherNewO.sayHi();
六、组合寄生式,组合式会调用两次超类型的构造函数,组合寄生则只调用一次
function inherit(subtype, superType){
var o = object(super.prototype);
o.constructor = subtype;
subtype.prototype = o;
}
//例如:
function Super(name){
this.name = name;
}
Super.prototype.sayName = function(){
console.log(this.name);
};
function Sub(name, cardNo){
Super.call(this, name);
this.cardNo = cardNo;
}
inherit(Sub, Super);
sub.prototype.sayHello = function(){
console.log('Hello');
}