JavaScript 函数方法 - bind()

Function.prototype.bind()

  ECMAScript5中新增的方法,但是在ECMAScript3可以通过模仿实现其方法作用

 作用:

  bind() 方法会创建一个新函数,当这个新函数被调用时,它的this值是传递给bind()的第一个参数, 它的参数是bind()的其他参数和其原本的参数.

 基本语法

fun.bind(thisArg[, arg1[, arg2[, ...]]])

/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;

  参数

  thisArg

    当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用new 操作符调用绑定函数时,该参数无效。

  arg1, arg2, ...

    当绑定函数被调用时,这些参数加上绑定函数本身的参数会按照顺序作为原函数运行时的参数。

   返回值

        返回由指定的this值和初始化参数改造的原函数拷贝

 

  描述:

  1. bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体。
  2. 目标函数 被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。
  3. 绑定函数被调用时,bind() 也接受预设的参数提供给原函数。
  4. 一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

 

  首先要理解几个概念, 绑定函数、 目标函数 

  先看看下面的实例:

var  origin = function() { 
        console.log(this.x, this.y); 
    };

var o = { x: 1, y: 2 };

var bindFun = origin.bind(o);

bindFun();

  origin 目标函数(原函数) bindFun 绑定函数 明白这几个函数所代指的对象。 那么逐一来看看描述上每一句话的含义;

 <1> 绑定函数 与 目标函数 具有相同的方法体; 

   

var sum = function() {
    console.log("12345");
};

var succ = sum.bind();
sum(); //12345
succ(); //12345

从上述打印的结果看出,确实可以验证,它们具有相同的方法体。

<2> 当目标函数被调用时,其 this 会绑定到 bind()函数的第一个参数,该参数不能被重写

  

var sum = function() {
    console.log(this.x, this.y);
};

var succ = sum.bind({ x: 1, y: 2 });
succ(); // 1 2

 <3> 绑定函数被调用时,bind() 也接受预设的参数提供给原函数

var sum = function(z) {
    console.log(this.x, this.y, z);
};

var succ = sum.bind({ x: 1, y: 2 }, 3);
succ(); // 1 2 3

<4> 一个绑定函数也能使用 new 操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

var sum = function(z) {
    console.log(this.x, this.y, z);
};

var succ = sum.bind({ x: 1, y: 2 }, 3);
new succ(); // undefined undefined 3

 

  如何在ECMAScript3中模拟实现 bind()函数效果

 

if (!Function.prototype.bind) {
    Function.prototype.bind = function(o /*,org*/ ) {
        var self = this,
            boundArgs = arguments;
        return function() {
            //创建一个实参列表,将传入 bind() 的第二个及后续的实参都传入这个函数
            var args = [],
                i;
            for (i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
            for (i = 0; i < arguments.length; i++) args.push(arguments[i]);

            return self.apply(o, args);
        };
    };
}

 

 

兼容旧的浏览器方式

  bind 函数在 ECMA-262 第五版才被加入;它可能无法在所有浏览器上运行。你可以部份地在脚本开头加入以下代码,就能使它运作,让不支持的浏览器也能使用 bind() 功能。

if (!Function.prototype.bind) {
    Function.prototype.bind = function(oThis) {
        if (typeof this !== "function") {
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }
        var aArgs = Array.prototype.slice.call(arguments, 1), //获取参数
            fToBind = this, // 保存外部 this
            fNOP = function() {}, // 主要用在判断是否为函数实例
            fBound = function() {
                return fToBind.apply(this instanceof fNOP ? //防止 call apply 方式调用
                    this :
                    oThis || this, //从这里可以看出 oThis 是可选的 当没有传递时,默认是当前上下文对象
                    aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype; // 保持与目标函数一直 
        fBound.prototype = new fNOP(); // 给绑定函数原型赋值

        return fBound;
    };
}

 

posted @ 2016-09-22 11:44  czhyuwj  阅读(565)  评论(0编辑  收藏  举报