過去には、self = thisまたはthis = 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コンテキストを維持するために、これは設定されている変数です。
コードコピーは次のとおりです。
render:function(){
this.getasyncdata(function(){
this.specialFunction();
this.anotherspecialFunction();
} .bind(this));
}
.bind()を呼び出すと、単に新しい関数を作成し、これをこの関数に渡します。 .bind()を実装するコードは、ほぼこのようなものです。
次のようにコードをコピーします:function.prototype.bind = function(scope){
var fn = this;
return function(){
fn.apply(scope);
};
}
function.prototype.bind()を使用する簡単な例を次に示します。
コードコピーは次のとおりです。
var foo = {
X:3
};
var bar = function(){
console.log(this.x);
};
bar(); //未定義
var boundfunc = bar.bind(foo);
boundfunc();
とても便利ではありませんか?残念ながら、IE8以下のIEブラウザはfunction.prototype.bind()をサポートしていません。サポートされているブラウザには、Chrome 7+、Firefox 4.0+、IE 9+、Opera 11.60+、Safari 5.1.4+が含まれます。 IE 8/7/6および他のブラウザはそれをサポートしていませんが、Mozilla開発グループは、コードを次のように、IEブラウザの古いバージョンの同様の機能を持つ関数を書きました。
コードコピーは次のとおりです。
if(!function.prototype.bind){
function.prototype.bind = function(othis){
if(typeof this!== "function"){
// ecmascriptに可能な最も近いもの5内部等価関数
新しいTypeError( "function.prototype.bind-拘束されようとしているものは呼ばれない");
}
var aargs = array.prototype.slice.call(arguments、1)、
ftobind =これ、
fnop = function(){}、
fbound = function(){
ftobind.applyをreturn(このインスタンスのfnop && othis
? これ
:othis、
aargs.concat(array.prototype.slice.call(arguments)));
};
fnop.prototype = this.prototype;
fbound.prototype = new fnop();
fboundを返します。
};
}