如何在对象字面量中使用“this”关键字?

How do I use 'this" keyword in an object literal?

如果我在同一个对象中声明了一个对象和一个函数,我该如何使用this访问对象,使用函数?
示例:

var foo = {
    bar: function () { this.tail = 'torn'; },
    qux: new this.bar() {}
}
// foo.qux instanceof bar => true
// foo.qux.tail = 'torn' => true

我不能使用this,我该怎么办?

您没有将函数和对象分配给您正在重新定义符号 foo 绑定到的同一个变量。每次设置 foo = 时,您都会将右侧的内容绑定到该符号。您不能使用 this 访问该函数,因为它是一个不同的对象。如果你想要一个有函数的对象,你必须像这样定义它

var foo = {
     myVal: 123,
     myFunction: function(){ return this.myVal;}
   }