国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-20 20:51:55
字體:
供稿:網(wǎng)友

以前,你可能會(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;
  };
}

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 大石桥市| 新晃| 增城市| 雷山县| 满洲里市| 嘉峪关市| 如皋市| 麻城市| 博兴县| 荆门市| 天峻县| 山东省| 寻乌县| 赤壁市| 武夷山市| 厦门市| 长汀县| 漠河县| 盐山县| 衡南县| 洛阳市| 奉贤区| 台北县| 东辽县| 阳春市| 麻栗坡县| 吉安县| 荥阳市| 襄樊市| 宝山区| 马鞍山市| 颍上县| 柘城县| 拉孜县| 神木县| 平南县| 东乡族自治县| 农安县| 东源县| 旺苍县| 行唐县|