Javascript bind()引用了错误的对象

Javascript bind()引用了错误的对象,javascript,Javascript,我已经为您解释了这个问题,只需查看我上面代码中的注释,提前感谢您的代码没有任何意义。除非您正在使用Transpiler或代码生成器,否则不要使用像bind()这样的黑魔法规范函数 在编写完全正常的代码时,只需利用JS已经允许的功能: this不会在对象初始化器中引用您的对象,因为该对象尚不存在,并且您不在该对象的执行上下文中,因此您绑定了错误的thisArg在bind中的this不在方法(或对象上的函数)中,因此,此时它的值不会更改为my_object。相关:。对象文字不创建引用它们所表示的对象

我已经为您解释了这个问题,只需查看我上面代码中的注释,提前感谢

您的代码没有任何意义。除非您正在使用Transpiler或代码生成器,否则不要使用像
bind()
这样的黑魔法规范函数

在编写完全正常的代码时,只需利用JS已经允许的功能:


this
不会在对象初始化器中引用您的对象,因为该对象尚不存在,并且您不在该对象的执行上下文中,因此您绑定了错误的
thisArg
bind
中的
this
不在方法(或对象上的函数)中,因此,此时它的值不会更改为
my_object
。相关:。对象文字不创建引用它们所表示的对象的
this
。那不是一件事<代码>这个在它们的内部和外部都是相同的。什么。。。你真的想在这里做什么?这段代码有什么可能的用途是普通代码无法为您完成的?创建一个对象类,创建一个
my_对象
实例,然后。。。完成?只需编写普通代码,
将指向函数中的对象。在没有
bind()
的示例中,您将获得正确的
,因为它基于调用方式,而不是设置方式。因此,当您执行
my\u object.my\u function()
时,您会看到
my\u object
,因为这就是您正在调用的函数。另一个例子是,尝试执行
test\u func=my\u object.my\u函数console.log(test_func())
,您将看到
窗口
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
// 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