嵌套在原型(prototype)函数下的函数不会获得为原型(prototype)定义的 this.variables。
var Person, p;
Person = function(name, age) {
this.name = name;
this.age = age;
};
Person.prototype.getInfo = function() {
var innerFun;
innerFun = function() {
return this.name;
};
return "name: " + (innerFun()) + " age: " + this.age;
};
p = new Person('dork', 99);
console.log(p.getInfo()); // name: age: 99
我认为既然每个函数都是一个对象,this 在每个函数定义中都会不同;但是下面的代码打破了这个逻辑。
var getInfo;
getInfo = function() {
var display;
this.name = 'dork';
return display = function() {
return this.name;
};
};
console.log(getInfo()()); // dork
此行为背后是否存在逻辑,或者我应该将其作为规则并使用 call() 来解决此问题?
最佳答案
这个
行为的简短版本:
- 在作为
x.f()
调用的函数中,this
将是x
。
(注意:调用作为x.f()
。无论您如何以及在何处定义它都无关紧要) - 在作为
f()
调用的函数中,this
将是window
。 - 在作为
x['f']()
调用的函数中,this
将是window
x
(不知道为什么我不这么认为) - 在作为
f.call(x)
或f.apply(x)
调用的函数中,this
将是x
。
同样,原型(prototype)并不重要,如果你这样做的话
var f = p.getInfo;
console.log(f());
您会发现只有调用风格很重要。
关于javascript - 嵌套在原型(prototype)函数下的函数表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016841/