function inheritPrototype(subType,superType){
var prototype = object(superType.prototype);
prototype.constructor = subType;
//将原型指向sub对象
subType.prototype = prototype;
}
function object(o){
//创建一个空的构造函数
function F(){};
//空构造函数的原型对象指向o这个对象
F.prototype = o;
return new F();
}
//父类
function Father(){
this.name = 'zhang';
this.color = ['red','green'];
}
Father.prototype.sayName = function({console.log(this.name)}
//子类
function Son(){
//call 借用父类构造函数
Father.call(this);//自动执行改变this指向
this.age=18;
}
inheritPrototype(Son,Father);
var son = new Son();
console.log(son.color);
本文介绍了一种使用JavaScript实现继承的方法,通过定义父类Father和子类Son,并利用自定义函数实现原型链继承,展示了如何在子类中继承父类的属性和方法。
238

被折叠的 条评论
为什么被折叠?



