代码之家  ›  专栏  ›  技术社区  ›  Susan

解释约翰·雷西格的忍者密码

  •  9
  • Susan  · 技术社区  · 15 年前
    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" );
    

    下面对Jeffery代码的微小修改帮助我理解内部匿名函数中使用的参数。我刚换了下面三行

    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");  
    

    谢谢大家

    5 回复  |  直到 15 年前
        2
  •  6
  •   Alex Barrett    15 年前

    Array.prototype.slice.call(arguments) Array

        3
  •  6
  •   Jeffrey Hantin    15 年前

    Function bind this

    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"
    
        4
  •  1
  •   Allen Rice 0x6A75616E    15 年前

    Array.slice(begin[,end])

    trees = ["oak", "ash", "beech", "maple", "sycamore"] 
    document.write(trees.slice(1,4)) 
    


    trees = ["oak", "ash", "beech", "maple", "sycamore"] 
    document.write(trees.slice(1,-2)) 
    

        5
  •  -1
  •   cdmckay    15 年前

    arguments Array args.shift()

    length