JavaScript中原型链十分重要。 为方便直观感受js中原型链的调用,举例验证。以下为代码:
function Pet(name,age){
if(this instanceof Pet===true&&name&&age){
this.name=name;
this.age=age;
}
}
Pet.prototype.play=function(){
console.log("Your pet "+this.name+" wants to play with you!");
}
Pet.prototype.say=function(words){
console.log("Your pet "+this.name+" is saying "+words+" to you!");
}
function Cat(name,age,sex){
if(this instanceof Cat===true&&age&&name){
Pet.call(this,name,age);
this.sex=sex;
}
}
Cat.prototype=Object.create(Pet.prototype);
Cat.prototype.constructor=Cat;
Cat.prototype.play=function(){
console.log("Cat "+this.name+" is playing with you!");
}
Cat.prototype.say=function(word){
Pet.prototype.say.apply(this,arguments);
}
var m=new Pet("Cindy",3);
var ming=new Cat("Cindy",3,"girl");
m.play();
ming.play();
m.say("hi");
ming.say("miao");
下面为浏览器控制台输出结果:
由以下语句将Cat的原型链接为Pet:
Cat.prototype=Object.create(Pet.prototype);
Cat.prototype.constructor=Cat;
也可使用该语句,效果类同:
Cat.prototype=new Person();
Cat.prototype.constructor=Cat;
继承基类的属性及方法可使用call,apply,效果类同,方法有差别,可见上例。
勤加练习,多多感悟,与君共同进步!