解释John Resig的一些忍者代码

Sus*_*san 9 javascript

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)

感谢大家

CMS*_*CMS 8

参数对象是类似阵列的对象,它仅具有长度属性.

通过Array.prototype调用slice函数是将其转换为数组的常用技术,因此您可以直接在此示例中使用数组函数,如shiftconcat.

  • @CMS Nope,`arguments`仍然继承自ES5中的`Object.prototype`,而不是来自`Array.prototype`.你也忘记了相当有用(虽然有点不合理)**`arguments.callee`**:) (3认同)

Ale*_*ett 6

Array.prototype.slice.call(arguments)创建一个Array包含传递给函数的所有参数.


Jef*_*tin 6

此代码在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)