我以为我知道JavaScript,似乎我不知道。
我想定义一个像这样的对象。 (来自http://www.phpied.com/3-ways-to-define-a-javascript-class/)
的例子var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
嗯,这看起来很好,让我们打印信息......
apple.getInfo() //returns "red macintosh apple" as expected
好的,现在取出该功能并再次运行......
var func = apple.getInfo; func(); //returns "undefined undefined apple"
嗯,这不是我的预期。显然,this
被解释为window
。这不是我想要的。
我的问题是 - 重写apple
文字的惯用首选方法是什么,以便apple.getInfo
返回一个可以单独运行但仍然使用对象属性的函数? / p>
答案 0 :(得分:6)
this
的工作方式取决于它的调用方式。了解this
是什么的快速提示是在调用中的函数名称之前查看对象。
执行apple.getInfo()
会使this
引用apple
。但是将其称为func()
就像调用window.func()
一样(假设它在全局空间中),这使this
引用window
。
如果你想"强迫" this
对函数的值,然后执行bind
。它创建了一个函数的副本,强制this
作为传递的第一个参数。
var func = apple.getInfo.bind(apple);
// all calls to `func` will have `this` "forced" as `apple`
如果您想在通话中指定this
但不会永久篡改this
上的func
(就像bind
这样做),您可以使用{{1 }或call
:
apply
答案 1 :(得分:1)
@Joseph梦想家提出了一个很好的答案。
由于OP正在寻找一种方法让apple.getInfo
始终返回一个没有undefined
问题的函数,我想我会抛出这个替代方案。< / p>
var apple = {
type: "macintosh",
color: "red"
};
apple.getInfo = (function () {
return this.color + ' ' + this.type + ' apple';
}).bind( apple );
这样,每次要创建对该函数的新引用时,都不必调用apple.getInfo.bind(apple)
。
请注意,您无法将getInfo
放在原始对象文字中,因为此时apple
没有为其分配值,而.bind( apple )
赢了&{{1}} #39;工作正常。