<body>
 <a href='#'>Linked</a>
  <script>
    var bind = function( fun, thisp ) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return fun.apply(thisp, args.concat(Array.prototype.slice.call(arguments)));
}
};
function doubleCheck() {
this.message = 'Are you sure want to leave? ';
}
doubleCheck.prototype.sayGoodBye = function(str) {
return confirm(this.message + ' ' + str);
}
function initPage() {
var clickedLink = new doubleCheck();
var links = document.getElementsByTagName('a');
var $B = bind(clickedLink.sayGoodBye, clickedLink, 'parm1'); // 这里使用了bind
for(var i = 0; i < links.length; i++) {
links[i].onclick = $B;
}
} window.onload = initPage;
  </script>
 </body>
这里注释处 我用了bind方法绑定了指针. 但bind方法的
return fun.apply(thisp, args.concat(Array.prototype.slice.call(arguments)));
这段代码不太理解 这里的concat(Array.prototype.slice.call(arguments)) 这个参数获取 在什么情况下才能用到啊?

解决方案 »

  1.   


               return function() {
                    return fun.apply(thisp, args);
                }
    // 我认为这样不就可以了么? 为啥还要获取执行的那个函数的参数 什么时候会有这种情况?
      

  2.   

    可以看一下 下面的例子   参数除了能在bind的时候传入
    也可以在bind函数执行后返回的函数g   执行的时候传入参数如果只是return fun.apply(thisp, args);
    g执行的时候就不能传入参数
    var bind = function( fun, thisp ) {
    var args = Array.prototype.slice.call(arguments, 2);
    return function() {
    return fun.apply(thisp, args.concat(Array.prototype.slice.call(arguments)));
    //return fun.apply(thisp, args); 拿这个在看看运行结果 }
    };
    var c= {
    a:'a',
    b:function(c,b){
    return c+b+this.a;
    }
    }
    var d = {a:" xiongdi "};
    var g = bind(c.b,d,' ni ')
    alert(g(" hao "));
      

  3.   

    我知道wtcsy的意思. 但面向对象这样用bind一般都是绑定事件之类的.
    显然一般是这样用   var $$B = Bind(fun, obj, param1, param2);
       obj.onclick = $$B;
     // 显然不能让$$B去运行 也就是
       obj.onclick = $$B('hello'); // 这样就没有绑定的意义了 就直接运行了.问下wtcsy 在你编写代码的时候 使用过 $$B('hello')这样的第二次绑定么?
      

  4.   

    但面向对象这样用bind一般都是绑定事件之类的.???这是谁说的啊????你非要从元素绑定事件上理解    那这么写确实没意义比如一个方法    在你的项目中很公共      而函数里面有this还不是用bind来改变里面this的指向