亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript中的prototype.bind()方法介紹

 更新時(shí)間:2014年04月04日 15:20:55   作者:  
在JavaScript中,我們經(jīng)常用到函數(shù)綁定,而當(dāng)你需要在另一個(gè)函數(shù)中保持this上下文時(shí),使用Function.prototype.bind()會(huì)很方便

以前,你可能會(huì)直接設(shè)置self=this或者that=this等等,這樣做當(dāng)然也能起作用,但是使用Function.prototype.bind()會(huì)更好,看上去也更專業(yè)。
下面舉個(gè)簡(jiǎn)單的例子:

復(fù)制代碼 代碼如下:

var myObj = {
    specialFunction: function () {
    },
    anotherSpecialFunction: function () {
    },
    getAsyncData: function (cb) {
        cb();
    },
    render: function () {
        var that = this;
        this.getAsyncData(function () {
            that.specialFunction();
            that.anotherSpecialFunction();
        });
    }
};
myObj.render();

在這個(gè)例子中,為了保持myObj上下文,設(shè)置了一個(gè)變量that=this,這樣是可行的,但是沒有使用Function.prototype.bind()看著更整潔:
復(fù)制代碼 代碼如下:

render: function () {
    this.getAsyncData(function () {
        this.specialFunction();
        this.anotherSpecialFunction();
    }.bind(this));
}

在調(diào)用.bind()時(shí),它會(huì)簡(jiǎn)單的創(chuàng)建一個(gè)新的函數(shù),然后把this傳給這個(gè)函數(shù)。實(shí)現(xiàn).bind()的代碼大概是這樣的:

復(fù)制代碼 代碼如下:
Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}

 

下面在看一個(gè)簡(jiǎn)單的使用Function.prototype.bind()的例子:

復(fù)制代碼 代碼如下:

var foo = {
    x: 3
};

var bar = function(){
    console.log(this.x);
};

bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3

 

是不是很好用呢!不過遺憾的是IE8及以下的IE瀏覽器并不支持Function.prototype.bind()。支持的瀏覽器有Chrome 7+,F(xiàn)irefox 4.0+,IE 9+,Opera 11.60+,Safari 5.1.4+。雖然IE 8/7/6等瀏覽器不支持,但是Mozilla開發(fā)組為老版本的IE瀏覽器寫了一個(gè)功能類似的函數(shù),代碼如下:

復(fù)制代碼 代碼如下:

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable 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,
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

相關(guān)文章

最新評(píng)論