function Super(){
this.name = "this is super";
}
Super.prototype = {
say:function(){
console.log(this.name);
}
}
function Sub(){
this.name = "this is sub";
}
Sub.prototype = new Super();
var o = new Sub();
o.say(); //this is sub
实例 o 的原型对象的constructor是Super,那么 this.name 应该是Super的构造函数。但是输出是 this is sub
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
方法是从原型链中继承来的没错。然而方法体中的
this是什么,与这个方法来自哪里没有关系,而是跟方法调用方式有关。你是用o调用的,所以this就是o,就是你new出来的Sub实例。所以
this.name首先是到你的o上面去找,找不到再沿原型链向上查找。o->Sub->Super
你要是不在Sub构造函数里面加上
那就能得到 this is super.
翻看一下js 原型链的知识- -
无论
o.say()的say()方法是从哪里继承下来的其函数内部的指令肯定是
console.log(this.name);这里的这句命令,会被带回到调用者那里。
this也会指向 调用者o此时
o根据原型链最近的方法调用了say函数所以会输出
"this is sub"@linkFly