首先定义一个构造类:
function Father(){
this.adress = '深圳';
this.getAdress = function(){
console.log('住在'+this.adress)
}
}
在其原型上添加一个自定义方法:
Father.protootype.getMoney =function() {
console.log('有很多钱')
}
一、原型链继承:子类的原型指向父类的实例
function Son(){
}
Son.prototype = new Father();
Son.prototype.name = ‘son1’;
var son1 = new Son();
console.log(son1.adress);//深圳
console.log(son1.getAdress ());//住在深圳
console.log(son1.getMoney ());//有很多钱
console.log(son1 instanceof Father); //true
二、构造继承:假继承
function Son(name){
Father.call(this);
this.name = 'son2';
}
var son2= new Son();
console.log(son2.name);//’son2’
console.log(son2 instanceof Father); // false
console.log(son2 instanceof son); // true
三、组合继承
function Son(){
Father.call(this);
this.name = 'son3';
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
var son = new Son();
console.log(son.name);//’son3’
console.log(son instanceof Father); // true
console.log(son instanceof Son); // true
四、寄生组合继承:去除父类的实例属性和方法
function Son(){
Father.call(this);
this.name = 'son4';
}
(function(){
// 创建一个没有实例方法的类
var F= function(){};
F.prototype = Father.prototype;
//将实例作为子类的原型
Son.prototype = new F();
Son.prototype.constructor = Son;
})();
var son= new Son();
console.log(son.name);
console.log(son instanceof Father); // true
console.log(son instanceof Son); //true
来源:https://www.cnblogs.com/peikun1026/p/9351471.html