首页 > 开发 > JS > 正文

js里面的call的问题

2017-09-05 05:51:26  来源:网友分享

为什么这句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();

解决方案

  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"。