为什么这句superSay.call(this);
就可以让浏览器先提示"Hello",然后再"stu-Hello"呢
function People(){
}
People.prototype.say = function(){
alert("Hello");
}
function Student(){
}
Student.prototype = new People();
var superSay = Student.prototype.say;
Student.prototype.say = function (){
superSay.call(this);
alert("stu-Hello");
}
var s = new Student();
s.say();
var superSay = Student.prototype.say;
这一句将superSay这个变量指向了People.prototype.say
这个方法,因为Student.prototype = new People();
,所以Student.prototype.say
最终指向的是其原型链上的say方法,也就是People.prototype.say
。然后在
Student.prototype
这个对象上又重新定义了say方法,正常情况下,这个say方法会隐藏原型链上的People.prototype.say
这个方法,但前面的superSay已经保留了People.prototype.say
这个方法的引用,因此superSay.call(this);
会执行People.prototype.say
这个方法,所以先提示"Hello",然后再"stu-Hello"。