js继承的关系多,而且拥有不同的特点。同时也是必须了解掌握的知识点。首先,要先知道什么是构造函数?
构造函数
构造函数和普通函数的区别:仅在于调用方式不同,任何函数,只要通过 new 操作符来调用,那它可以作为构造函数;任何函数,如果不通过 new 操作符有来调用,那么它是一个普通函数。
实例拥有 constructor(构造函数)属性,该属性返回创建实例对象的构造函数。注:除了基本类型的 constructor 外( null 和 undefined 无 constructor 属性),constructor 可以被重写的。因此检测对象类型时。instanceof 操作符比 constructor 更可靠。
function Person(name,age){
this.name=name;
this.age =age;
}
var Kaiser =new Person(‘kaiser‘,22) ;
console.log(Kaiser.constructor === Person); //true
原型
function Person2(name){
this.name = name;
}
Person2.prototype.sayName = function(){
console.log(this.name)
}
var name1 = new Person2(‘kaiser‘);
var name2 = new Person2(‘lindang‘);
//构造函数的原型对象上方法和属性被实例共享
name1.sayName(); //kaiser
name2.sayName(); //lindang

实例.__proto__ === 构造函数.prototype
function SuperType(){
this.name = ‘kaiser‘
this.colors = [‘red‘,‘yello‘,‘green‘];
}
SuperType.prototype.getName = function(){
return this.name;
}
function SubType(){}
SubType.prototype = new SuperType(‘dog‘);
SubType.prototype.constructor = SubType;
let instance = new SubType();
instance.colors.push(‘white‘);
let instance2 = new SubType();
console.log(instance.colors) //[‘red‘,‘yello‘,‘green‘,‘white‘]
console.log(instance2.colors) //[‘red‘,‘yello‘,‘green‘,‘white‘]
function SuperType1(name){
this.name = name;
this.colors = [‘red‘,‘green‘,‘pink‘];
}
function SubType1(name){
SuperType1.call(this,name)
}
let instance3 = new SubType1(‘kaiser‘);
instance3.colors.push(‘white‘);
let instance4 = new SubType1();
console.log(instance3.name,instance3.colors); //kaiser,["red", "green", "pink", "white"]
console.log(instance4.name,instance4.colors) //undefined,["red", "green", "pink"]
组合继承
function SuperType2(name){
this.name = name;
this.colors = [‘pink‘,‘blue‘,‘yellow‘];
}
SuperType2.prototype.sayName = function(){
return this.name;
}
function SubType2(name,age){
SuperType2.call(this,name);
this.age = age;
}
SubType2.prototype = new SuperType2();
SubType2.prototype.constructor = SubType2;
SubType2.prototype.sayAge = function(){
return this.age
}
let instance5 = new SubType2(‘kaiser‘,22);
instance5.colors.push(‘red‘);
let instance6 = new SubType2(‘liming‘,20);
console.log(instance5.colors,instance5.sayAge()); // [‘pink‘,‘blue‘,‘yellow‘,‘red‘] 22
console.log(instance6.colors,instance6.sayName()); //[‘pink‘,‘blue‘,‘yellow‘] liming
原文:https://www.cnblogs.com/Arthur123/p/11218806.html