Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
var myObject = {};
function myFunction(){
return this == myObject;
}
assert( !myFunction(), "Context is not set yet" );
var aFunction = myFunction.bind(myObject)
assert( aFunction(), "Context is set properly" );
Run Code Online (Sandbox Code Playgroud)
下面对Jeffery代码的微小修改帮助我理解了内部匿名函数中使用的参数.我只是改变了下面的3行
var introduce = function(greeting) { alert(greeting + ", my name is " + this.name + " ,home no is " + arguments[1]); }
hiBob(" 456"); // alerts "Hi, my name is Bob"
yoJoe(" 876");
Run Code Online (Sandbox Code Playgroud)
感谢大家
此代码在Function名为的类型上创建一个新方法,该方法bind接受一个自由函数作为输入,并返回一个包装函数,该函数调用它,就像它是指定对象上的方法一样.这与.Net委托如何将函数及其相关this引用包装在一起非常相似.
另外,如果提供了多个参数bind,则这些附加参数会被添加到调用之前 - 这种技术也称为currying.
要尝试以更简单的方式解释它,请考虑以下事项:
var bob = { name: "Bob" };
var joe = { name: "Joe" };
var introduce = function(greeting) { alert(greeting + ", my name is " + this.name); }
var hiBob = introduce.bind(bob, "Hi");
var yoJoe = introduce.bind(joe, "Yo");
hiBob(); // alerts "Hi, my name is Bob"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1003 次 |
| 最近记录: |