Mootools 何时使用 Function.prototype.bind
Mootools when to use Function.prototype.bind
>我有一个非常基本的问题,我找不到答案,我确实查看了mootools网站,但我还没有完全掌握这个概念:
在mootools中,你有一个函数.bind(),它可以按如下方式使用:
function customFunction () {
this.setStyle('color','blue');
}
var boundFunction = customFunction.bind(myElement);
boundFunction(); //Now the color of the element is changed to red
// To show how bind works the following example:
var myBoundFunction = myFunction.bind(anyVar);
// is roughly equivalent with
var myBoundFunction = function(){
return myFunction.call(this);
};
但为什么不这样做呢?
function customFunction (parameter) {
parameter.setStyle('color','blue');
}
customFunction(myElement);
这似乎更有效率?
我最大的问题是:在哪里使用 .bind() 是一个好的做法,为什么会这样?
在将方法作为回调参数传递时,Bind 很有用。假设我们有以下user
对象:
function User(name) {
this.name = name;
}
User.prototype.sayHi = function() {
console.log("Hi, my name is "+this.name);
}
var user = new User("John");
现在我们想在有人点击某个div 元素时调用它的 sayHi
方法。我们可以尝试这样做:
$('userDiv').addEvent('click', user.sayHi);
但这行不通,因为我们只传递sayHi
函数本身,但它的上下文(this
的值)将丢失,并且函数将打印"Hi, my name is undefined"
。
为了保持上下文,我们可以改为:
$('userDiv').addEvent('click', function() { user.sayHi(); });
但是用bind
附加上下文要简单得多:
$('userDiv').addEvent('click', user.sayHi.bind(user));
相关文章:
- 直接在函数声明上使用function.prototype.bind
- requestAnimationFrame的Function.prototype.bind导致属性不可读
- 使用 Function.prototype.bind.apply(Obj, args) 将参数传递给对象,只传递第一个元
- 使用 Function.prototype.bind 或保存的引用
- Phantomjs Function.prototype.bind
- Function.prototype.bind with null 作为参数
- Mootools 何时使用 Function.prototype.bind
- Javascript: argument unpacking in function.prototype.bind()?
- 为什么使用Function.prototype.bind.apply
- JavaScript'有Ruby等价物吗;s函数.prototype.bind
- 在没有上下文参数的情况下调用本机绑定函数(function.prototype.bind)
- 为什么Function.prototype.bind很慢?
- 在EventListeners上使用function.prototype.bind()
- 为什么使用Function.prototype.bind而不是Function.prototype.call ?
- Function.prototype.bind
- Javascript Function.prototype.bind的变化我想确保我理解
- 在回调中可以替代function.prototype.bind
- 为什么Function.prototype.bind() "函数中的自定义属性
- Function.prototype.bind example
- Javascript Function.prototype.bind这是这个/如何找到这个