Javascript 失败(this.* 误导),?为什么

Javascript fail (this.* misdirected), ?why

在对象内部创建指向函数的指针时 "this" 未正确解析
试试这个例子来了解概念...

// this.* fail
a = { x : 123,  f : function(){ console.log( this.x ) } }
a.f()     // 123
b = a.f   // b points to a.f now
b()       // should print 123 but gaves 'undefined'

当您在实例上调用方法时,方法的上下文就是实例(f 方法中的 this 关键字是对 a 的引用,当执行 a.f()).

然而,当你在一个变量中保留对函数的引用时,调用它时,你实际上失去了上下文,所以 this 变成了全局上下文(在浏览器中是 window ).

因此,由于 callapply 方法,您需要在调用函数时为其提供上下文:

Function.prototype.call

Function.prototype.apply

您的代码变为:

b = a.f;
b.call(a); // or b.apply(a)

来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this.

Function context

Inside a function, the value of this depends on how the function is called.

Simple call

function f1(){
  return this;
}

f1() === window; // global object

这就是你在第二种情况下所做的b()。您基本上是在全局对象上调用 x 。所以

var x = 456;
// this.* fail
a = { x : 123,  f : function(){ console.log( this.x ) } }
a.f()     // 123
b = a.f   // b points to a.f now
b()       // prints 456

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

这是第一种情况。

您可以使用 bind:

b = a.f.bind(a);
b(); // 123

来自MDN

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

您可以尝试将其分配给对象中的某个变量:

var a = {
   x : 1,
   self : this,
   f : function() {
      self.x++;       
   },
   show : function() {
      alert(self.x);
   }
}

a.f();    
a.show();      

d = a.show;
d();