JavaScriptの中のprototype.bindの方法紹介


以前は、self=this=that=thisなどを直接設定することもありますが、それはもちろん役に立つと思いますが、Function.prototype.bindを使った方がいいと思います。専門的にも見えます。簡単な例を以下に挙げます。

var myObj = {
    specialFunction: function () {
    },
    anotherSpecialFunction: function () {
    },
    getAsyncData: function (cb) {
        cb();
    },
    render: function () {
        var that = this;
        this.getAsyncData(function () {
            that.specialFunction();
            that.anotherSpecialFunction();
        });
    }
};
myObj.render();
この例では、myObjコンテキストを維持するために、変数that=thisを設定しても良いが、Funtion.prototype.bindを使用していないので、より綺麗に見える:

render: function () {
    this.getAsyncData(function () {
        this.specialFunction();
        this.anotherSpecialFunction();
    }.bind(this));
}
ビnd()を呼び出すと、新しい関数を簡単に作成して、この関数にパスします。実装.bind()のコードは大体こんなものです。
Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}
 
簡単なFuntions.prototype.bind()の例を見てみます。

var foo = {
    x: 3
};

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

bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3
 
とても使いやすいですか?残念ながら、IE 8及び以下のIEブラウザはFuntions.prototype.bind()をサポートしていません。サポートされているブラウザは、Chrome 7+、Firefox 4.0+、IE 9+、Opera 11.60+、Safari 5.1.4+。IE 8/7/6などのブラウザはサポートしていませんが、Mozilla開発グループは古いバージョンのIEブラウザのために機能の類似の関数を書いています。コードは以下の通りです。