我正在创建一个函数,它已经给出了两个参数。我想绑定(bind)一个也会被传入的变量。
this.listenTo(this.topView,this.directionChosen.bind('top');
this.listenTo(this.leftView,this.directionChosen.bind('left');
this.listenTo(this.rightView,this.directionChosen.bind('right');
this.listenTo(this.bottomView,this.directionChosen.bind('bottom');
directionChosen:function(item,move,direction) {
}
是否可以绑定(bind)变量/属性并将其作为函数中的方向传递?
我一直在这样做,但可能做得不对。 谢谢
最佳答案
如果你看doc for .bind()
,您可以看到它需要一个或多个参数。第一个参数是您要为函数调用设置的 this
指针。您必须将其作为第一个参数传递。之后的其他参数是可选的,并且将是传递给实际函数的第一个参数。
此外(我不太清楚你在问题中想要什么),你必须传递你想要传递的实际参数,而不是变量名。
所以,你这样做的方式是行不通的。您必须传递想要作为第一个参数的 this
值,并且您传递的任何其他参数将首先发送到函数,而不是最后。
您可以使用闭包来解决您的问题,这本质上与 .bind()
所做的事情相同,但在您自己的自定义闭包中,您可以使用函数参数执行任何您想要的操作。
// method to call
directionChosen: function(item,move,direction) {
}
// code to call our method with custom arguments
var self = this;
this.listenTo(this.mainView, function(item, move) {
self.directionChosen(item, move, 'top');
});
或者,如果 top
实际上是一个变量名,并且您希望将该变量的值作为参数传递(从您的问题中不清楚您想要哪个),它看起来像这样:
// code to call our method with custom arguments
var self = this;
this.listenTo(this.mainView, function(item, move) {
self.directionChosen(item, move, top);
});
如果您想经常使用这种挂起后的参数行为,您可以创建自己的自定义版本的 .bind()
来为您执行此操作。
Function.prototype.bindAfter = function(thisPtr /* one or more args */) {
var args = Array.prototype.slice.call(arguments);
var self = this;
args.shift();
return function() {
var newArgs = Array.prototype.slice.call(arguments).concat(args);
return self.apply(thisPtr, newArgs);
}
};
然后您可以像这样使用.bindAfter()
:
this.listenTo(this.topView,this.directionChosen.bindAfter(this, 'top'));
this.listenTo(this.leftView,this.directionChosen.bindAfter(this, 'left'));
this.listenTo(this.rightView,this.directionChosen.bindAfter(this, 'right'));
this.listenTo(this.bottomView,this.directionChosen.bindAfter(this, 'bottom'));
仅供引用,解决这个问题的暴力方法如下:
var self = this;
this.listenTo(this.topView, function(item, move) {
return self.directionChosen(item, move, 'top');
});
this.listenTo(this.leftView, function(item, move) {
return self.directionChosen(item, move, 'left');
});
this.listenTo(this.rightView, function(item, move) {
return self.directionChosen(item, move, 'right');
});
this.listenTo(this.bottomView, function(item, move) {
return self.directionChosen(item, move, 'bottom');
});
这实际上是创建 .bindAfter()
的新代码行更少。
您还可以创建一个专门针对这一问题的辅助函数:
function callWithDirection(thisPtr, direction) {
return function(item, move) {
return thisPtr.directionChosen(item, move, direction)
}
}
然后你可以像这样使用它:
this.listenTo(this.topView, callWithDirection(this, 'top'));
this.listenTo(this.leftView, callWithDirection(this, 'left'));
this.listenTo(this.rightView, callWithDirection(this, 'right'));
this.listenTo(this.bottomView, callWithDirection(this, 'bottom'));
关于javascript - 如何将变量绑定(bind)到函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25020567/