js里面的call的问题

为什么这句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();
阅读 2.6k
3 个回答
  1. var superSay = Student.prototype.say;这一句将superSay这个变量指向了People.prototype.say 这个方法,因为Student.prototype = new People();,所以Student.prototype.say最终指向的是其原型链上的say方法,也就是People.prototype.say

  2. 然后在Student.prototype这个对象上又重新定义了say方法,正常情况下,这个say方法会隐藏原型链上的People.prototype.say这个方法,但前面的superSay已经保留了People.prototype.say这个方法的引用,因此superSay.call(this);会执行People.prototype.say这个方法,所以先提示"Hello",然后再"stu-Hello"。

不然呢?。。。于情于理都是这个顺序,没get到你的点

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题