bind()指向错误的对象

时间:2019-06-27 21:54:37

标签: javascript

var my_object = {
    my_function: function() { return this }.bind( this /* which refers to 'my_object' */ )
}

// i get the 'window object' instead of 'my_object' which does not make sense to me , 
// i know that the my_function is already bound to my_object and i 
// know that i do not need to use bind() , i was only trying to understand
// what's  wrong with binding my_function to the same object again
console.log( my_object.my_function() ); 

/* i remove bind() this time */
my_object.my_function = function() { return this };
console.log( my_object.my_function() ); //i get 'my_object' this time which is expected but i should have got the same results above

我已经为您解释了该问题,请先查看上面代码中的注释,谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码没有意义。除非您正在使用编译器或代码生成器生成器,否则请不要使用诸如bind()之类的黑魔法规范函数。

编写完全正常的代码时,只需利用JS已经允许您执行的操作:

// create a normal modern JS class
class MyClass {
  myFunction() {
    return this; // by *definition* "this" will point to the instance you call it on.
  }
}

// create an instance:
let myObj = new MyClass ();

// and verify calling `.myFunction()` returned the correct thing. Which it *has* to.
console.log(myObj.myFunction() === myObj); // true
相关问题