Javascript文字对象表示法此对象名称

Har*_*per 2 javascript object-literal javascript-objects

我有一个像这样的对象文字:

var test = {
    one: function() {
    },
    two: function() {
        this.one(); // call 1
        test.one(); // call 2
    }
};
Run Code Online (Sandbox Code Playgroud)

two函数中的调用之间有什么区别(使用对象文字名称和使用对象this)?

Ate*_*ral 5

test始终在two函数闭包内绑定到变量,testthis取决于函数的调用方式.如果使用常规对象成员访问语法调用该函数,则this成为拥有该函数的对象:

test.two(); // inside, "this" refers to the object "test"
Run Code Online (Sandbox Code Playgroud)

您可以this使用Function.prototype.call以下命令更改值:

test.two.call(bar); // inside, "this" refers to the object "bar"
Run Code Online (Sandbox Code Playgroud)

但无论函数如何被调用,函数test内部的值都保持不变two.