javascript - js里面的call的问题

查看:83
本文介绍了javascript - 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();

解决方案

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

这篇关于javascript - js里面的call的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆