理解理解js对象继承的对象继承的N种模式种模式
本文分享了js对象继承的N种模式,供大家参考。
一、原型链继承一、原型链继承
function Person(){};
Person.prototype = {
constructor: Person,
name: "Oliver"
};
function People(){};
People.prototype = new Person();
People.prototype.constructor = People;
People.prototype.sayName = function(){
return this.name;
};
var ins = new People();
console.log(ins.sayName());
二、借用构造函数(伪造对象,经典继承)二、借用构造函数(伪造对象,经典继承)
1、无参数、无参数
function SuperType(){
this.color = ["red","yellow","white"];
}
function SubType(){
SuperType.call(this);
}
var instance1 = new SubType();
var instance2 = new SubType();
instance1.color.pop();
console.log(instance1.color); //["red", "yellow"] console.log(instance2.color); //["red", "yellow", "white"]
2、有参数、有参数
function SuperType(name){
this.name = name;
this.number = [21,32,14,1];
}
function SubType(name,age){
SuperType.call(this,name);
this.age = age;
}
var instance1 = new SubType("Oliver",18);
var instance2 = new SubType("Troy",24);
instance2.number.pop();
console.log(instance1.name + instance1.age + instance1.number); //Oliver1821,32,14,1
console.log(instance2.name + instance2.age + instance2.number); //Troy2421,32,14
三、组合继承(伪经典继承)三、组合继承(伪经典继承)
1、无参数、无参数
function SuperType(){
this.color = ["red","yellow","white"];
}
SuperType.prototype.sayColor = function(){
return this.color;