简体   繁体   English

对JavaScript中的bind()感到困惑

[英]Confused about bind() in javascript

I pulled the code below from this tutorial: tutorial 我从本教程拉到下面的代码: 教程

If you can bind this from a parent function to an anonymous inner function, then what do you do if you want to reference "this" in the anonymous inner function at some later time? 如果可以将其从父函数绑定到匿名内部函数,那么以后要在匿名内部函数中引用“ this”怎么办? Does "this" not exist for the anonymous inner function? 匿名内部函数是否不存在“ this”?

render: function () 
{

    this.getAsyncData(function () {

        this.specialFunction();

        this.anotherSpecialFunction();

    }.bind(this));

}

what do you do if you want to reference "this" in the anonymous inner function at some later time? 如果以后想在匿名内部函数中引用“ this”怎么办?

There is no way to refer to the value of this that the callback would have if we hadn't called .bind . 如果没有调用.bind则无法引用回调将具有的this的值。

However, you don't have to use .bind , there are other ways to use the this value of the "parent" function: How to access the correct `this` context inside a callback? 但是,您不必使用.bind ,还有其他方法可以使用“父”函数的this值: 如何在回调内部访问正确的`this`上下文?

Does "this" not exist for the anonymous inner function? 匿名内部函数是否不存在“ this”?

this is an implicit value in every function. this每个函数中的隐式值。 Which value it has is determined by how the function is called , unless the function is explicitly bound to a certain value (via .bind ). 除非函数被显式绑定到某个值(通过.bind ),否则它具有哪个值取决于函数的调用方式

For example, if you call a function "normally", such as func() , then this will refer to the global object ( window in browsers). 例如,如果你调用一个函数“正常”,如func()那么this将涉及全局对象( window中浏览器)。 The API documentation usually explains which value this has inside a callback. API文档通常解释其值this有所回调内部。 If it doesn't mention anything explicitly, then you can assume that this refers to the global object, which is not very useful in most cases, and thus it is no problem to "override" it via .bind . 如果没有明确提到任何东西,那么你可以认为this指的是全局对象,这是不是在大多数情况下是非常有用的,因此是没有问题通过以“越权”它.bind
But even if this is set to a specific value in the callback, that value is often also passed as argument to the callback. 但是即使this其设置为回调中的特定值,该值也经常作为参数传递给回调。 Being able to access the value via this is just for convenience. 能够通过this访问值只是为了方便。 But again, it depends on how the API is designed and is usually explained in the API documentation. 但同样,这取决于API的设计方式,通常会在API文档中进行说明。


For more information about this , have a look at the MDN documentation . 有关更多信息this ,看看在MDN文档

The this context is set every time a function is called. 每次调用函数时都会设置this上下文。 If there is no context (as is the case with most callbacks), then this is lost. 如果没有上下文(例如多数回调的情况下),那么this将丢失。

It is more common to see: 更常见的是看到:

var self = this;
// code using self instead of this here

The above is more browser-compatible due to .bind being relatively new. 由于.bind相对较新,因此以上内容与浏览器更具兼容性。

When you have an anonymous callback, this usually refers to the window object. 当您有匿名回调时, this通常是指window对象。 A good example is with setTimeout : 一个很好的例子是setTimeout

var someObject = {
    set: function() { /* ... */ },
    doSomething: function() {
        // right here, "this" is "someObject"
        setTimeout(function() {
            // whereas right here, "this" is "window"
        });
    }
}

A lot of people solve this conflict like this: 很多人这样解决冲突:

var someObject = {
    set: function() { /* ... */ },
    doSomething: function() {
        var that = this;

        setTimeout(function() {
            console.log(that) // => now it refers to "doSomething"
        });
    }
}

That's where bind comes into play. 这就是bind起作用的地方。

See this jsfiddle : 看到这个jsfiddle

var someObject = {
    set: function() { /* ... */ },
    doSomething: function() {
        setTimeout(function() {
            console.log(this) // => now it refers to "doSomething"
        }.bind(this));
    }
}

Edit 编辑

Felix Kling made a good comment on this answer. Felix Kling对这个答案发表了很好的评论。 For this answer, I'm assuming you're calling someObject.doSomething() , and not calling the doSomething() method a different context. 对于此答案,我假设您正在调用someObject.doSomething() ,而不是在不同的上下文中调用doSomething()方法。

If you can bind this from a parent function to an anonymous inner function, then what do you do if you want to reference "this" in the anonymous inner function at some later time? 如果可以将其从父函数绑定到匿名内部函数,那么以后要在匿名内部函数中引用“ this”怎么办?

You won't be able to, if you want to reference the outer this then set this to a variable and don't use bind. 你将不能够,如果你想引用外this然后设置this一个变量,并且不使用绑定。

var that = this;

Does "this" not exist for the anonymous inner function? 匿名内部函数是否不存在“ this”?

this always exists. this一直存在。

Simple example: 简单的例子:

this.name = 'Bob';

function sayHello() {
  return ['Hello,', this.name].join(' ');
}

console.log(sayHello()); // "Hello, Bob"
console.log(sayHello.bind({name: 'Ana'})()); // "Hello, Ana"

http://jsbin.com/xibis/1/edit http://jsbin.com/xibis/1/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM