bind()在这个例子中做什么? [英] What is bind() doing in this example?

查看:128
本文介绍了bind()在这个例子中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在javascript中包围部分应用程序,我找到了这个例子。

我有以下代码:

 var aPlusb = function(a,b) {
返回a + b;
}



如果我们这样做

  var  partial = aPlusb.bind( null  10 
partial( 6 ); // 输出:16



我的问题是,为什么即使我们改变'null'作为参数我们仍然会有相同的输出?

 var partial = aPlusb (假,10); 
partial(6); //输出16



这里有什么真正的绑定?



我尝试了什么:



我试图查看MDN bind()参考,它解释了方法,但它似乎太流行了我。

bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值,并在调用新函数时提供任何前面提供的给定参数序列

在这种情况下'this'是什么?

解决方案

bind的第一个参数 method是在返回的函数中使用 this 值时将返回的值。由于你的函数从不使用这个,所以它几乎无关紧要。



考虑一个简单的例子:

  var  person = {
name: John Smith
age: 42
sayHello: function (){
alert( Hello, + .name + 。您是 + .age + 岁。);
}
};



如果直接在对象上调用该函数,它将按预期工作:

< pre lang =Javascript> person.sayHello(); // 你好,John Smith。你已经42岁了。



如果你试图将这个功能作为回调来传递,那么它就不起作用了:

 setTimeout(person.sayHello, 100 );  //  你好,。您未定义年数。 



这是因为该函数在全局范围内执行。 变量指向窗口对象。



通过使用 bind ,您可以确保在正确的范围内调用该函数:

 setTimeout(person .sayHello.bind(person), 100 );  //  你好,John Smith。你今年42岁。 


I am trying to wrap my head around partial applications in javascript and I found this example.
I have the following code:

var aPlusb = function (a, b) {
    return a + b;
}


And if we do something like this

var partial = aPlusb.bind(null, 10)
partial(6);//output : 16


My question, is why even if we change 'null' as an argument we would still have the same output?

var partial = aPlusb(false, 10);
partial(6);//output 16


And what is really bind doing here?

What I have tried:

I have tried to look at MDN bind() reference and it explains the method but it just seems too vogue to me.
"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"
What is 'this' in this case?

解决方案

The first parameter to the bind method is the value that will be returned when you use the this value within the returned function. Since your function never uses this, it's mostly irrelevant.

Consider a simple example:

var person = {
    name: "John Smith",
    age: 42,
    sayHello: function(){
        alert("Hello, " + this.name + ". You are " + this.age + " years old.");
    }
};


If you call the function directly on the object, it works as expected:

person.sayHello(); // Hello, John Smith. You are 42 years old.


If you try to pass the function as a callback, however, it doesn't work:

setTimeout(person.sayHello, 100); // Hello, . You are undefined years old.


That's because the function is executed under the global scope. The this variable points to the window object.

By using bind, you can ensure that the function is called in the correct scope:

setTimeout(person.sayHello.bind(person), 100);  // Hello, John Smith. You are 42 years old.


这篇关于bind()在这个例子中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆