将`this`与对象文字一起使用

时间:2014-06-28 14:53:08

标签: javascript

我以为我知道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>

2 个答案:

答案 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;工作正常。