"这"当从本地函数对象调用函数时,它是不同的

时间:2017-09-09 08:58:09

标签: javascript prototype this

我编写了以下代码,我希望调用getFull()和useGetFull()来做同样的事情,因为useGetFull只是为getFull()获取一个函数对象并调用它。

function Person(name, family) {
    this.name = name;
    this.family = family;
}

Person.prototype.getFull = function() {
    console.log(this.name + " " + this.family);
};

Person.prototype.useGetFull = function() {
    const f = this.getFull;
    f();
    // f.call(this) works as expected
}

p = new Person("Bob", "Smith");
p.getFull();
p.useGetFull();

然而,他们不做同样的事情,因为内部使用GetFull(),"这"是全球对象。我注意到使用f.call(this)而不是f()按预期工作,但我不能理解为什么我必须使用它。为什么"这个"的价值?根据我调用函数的方式/位置而有所不同?

2 个答案:

答案 0 :(得分:1)

一个简单的规则:

a.b() //b called with context a
d.e() //e called with context d
c() // c called with no context ( so the global instead)

Javascripts上下文取决于函数的调用方式。

答案 1 :(得分:1)

如果您没有注意到,this.getFull()也可以。这是因为当您将函数作为对象(任何对象)的属性调用时,该函数的this将引用该对象,在{{1}的情况下,您调用该函数的对象},foo.bar(),如果是foothis.getFull()。这就是为什么这个例子按预期工作的原因:

this


但是,当一个函数被调用而不是作为对象的属性时,换句话说,当它没有以类似于function Person(name, family) { this.name = name; this.family = family; } Person.prototype.getFull = function() { console.log(this.name + " " + this.family); }; Person.prototype.useGetFull = function() { /* getFull is preceded by something, it is invoked through "this", so the "this" reference inside of getFull will be set to the "this" part in the statement "this.getFull()". */ this.getFull(); } p = new Person("Bob", "Smith"); p.getFull(); prints out Bob Smith p.useGetFull(); // prints out Bob Smith foo.bar()的方式被访问时,以foo["bar"]()之类的方式,即使foo()是对值为foo的变量的引用,例如示例中的x.y,其f()也将是this在浏览器中绑定到全局对象的对象是window

function Person(name, family) {
    this.name = name;
    this.family = family;
}

Person.prototype.getFull = function() {
    console.log(this.name + " " + this.family);
};

Person.prototype.useGetFull = function() {
    const f = this.getFull;
    /* this call is not preceded by any objects, it is a plain 
       traditional function call, it is a function invokation in its 
       simplest form. all functions invoked in this manner will have 
       their "this" reference set to the global object. */
    f();
}

p = new Person("Bob", "Smith");
p.getFull();
p.useGetFull();


如果您对this感兴趣(双关语),请转到here