//js继承之借用构造函数
//为了解决原型中包含引用类型值所带来的问题,我们用借用构造函数
function Father(){
this.colors = ["red" , "blue" , "yellow"];
}
function Son(){
//继承了Father
Father.call(this);
}
var instance1 = new Son();
instance1.colors.push("black");
console.log(instance1.colors);
var instance2 = new Son();
console.log(instance2.colors);
//在Son的实例对象上执行Father()函数中定义的所有对象初始化代码
//1、传递参数
var Father = function(name){
this.name = name;
}
var Son = function(age){
Father.call(this , "宝清老窖");
this.age = age;
}
var instance = new Son(30);
console.log(instance);
//2、构造偶函数的问题
//如果仅仅是借用构造函数,那么也将无法避免构造函数模式存在的问题
//方法都是在构造偶函数中定义的,因此函数服用就无从谈起了。
//而且在Father类的原型中定义的方法,对自雷对象是不可见的
//结果所有类型都只能使用构造函数模式
//所以很少单独使用借用构造函数
//-------------------------------------------
//js继承之组合继承
//组合继承也叫伪经典继承
//原型链+借用构造
var Father = function(name){
this.name = name;
this.colors = ['red' , 'yellow' , 'green'];
}
Father.prototype.sayName = function(){
console.log(this.name);
}
var Son = function(name , age){
//继承属性
Father.call(this , name);
this.age = age;
}
//继承方法
Son.prototype = new Father();
Object.defineProperty(Son.prototype , 'constructor' , {
enumerable: false,
value: Son
});
Son.prototype.sayAge = function(){
console.log(this.age);
}
var son1 = new Son('宝清老窖' , 20);
son1.colors.push('black');
console.log(son1);
console.log(son1.colors);
son1.sayName()
son1.sayAge()
var son2 = new Son('金宝清' , 29);
console.log(son2);
console.log(son2.colors);
son2.sayName()
son2.sayAge()
//js中最常用的继承模式