我以为我懂 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
返回一个可以单独运行的函数,但仍然使用对象属性?
最佳答案
this
的工作方式取决于它的调用方式。要了解 this
是什么,一个快速提示是查看调用中函数名称之前的对象。
执行apple.getInfo()
使this
引用apple
。但是将其调用为 func()
就像调用 window.func()
(假设它在全局空间中),这使得 this
引用到窗口
。
如果您想在函数上“强制”使用 this
的值,请执行 bind
。它创建函数的副本,并强制将 this
作为传递的第一个参数。
var func = apple.getInfo.bind(apple);
// all calls to `func` will have `this` "forced" as `apple`
如果您想在调用中指定 this
,但不想在 func
上永久篡改 this
(例如 bind
> 做到了),您可以使用 call
或 apply
:
var func = apple.getInfo;
func.call(apple);
func.apply(apple);
// Both function will have `this` as `apple` only for the call.
关于javascript - 将 `this` 与对象文字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24468004/