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

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 16:03:42
字體:
供稿:網(wǎng)友
在JavaScript中,我們經(jīng)常用到函數(shù)綁定,而當(dāng)你需要在另一個(gè)函數(shù)中保持this上下文時(shí),使用Function.prototype.bind()會很方便

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

復(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í),它會簡單的創(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è)簡單的使用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ā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 甘南县| 辽阳市| 永福县| 芦山县| 运城市| 抚顺市| 临城县| 唐河县| 盱眙县| 白山市| 迁安市| 凌海市| 盐亭县| 株洲市| 蒙阴县| 滦平县| 宜章县| 台东市| 安图县| 孝感市| 青龙| 清苑县| 东乡| 湘西| 胶南市| 阿拉善左旗| 哈巴河县| 雅江县| 三亚市| 儋州市| 沾化县| 抚松县| 广东省| 乌苏市| 涞水县| 临猗县| 玛曲县| 融水| 兰州市| 章丘市| 潞城市|