과거에는 Self = this 또는 this = this 등을 설정했을 수 있습니다. 물론 작동하지만 function.prototype.bind ()를 사용하는 것이 더 좋으며 더 전문적으로 보일 것입니다.
간단한 예는 다음과 같습니다.
코드 사본은 다음과 같습니다.
var myobj = {
특수 기능 : function () {
},
anotherspecialfunction : function () {
},
getasyncdata : function (cb) {
cb ();
},
렌더 : function () {
var that = this;
this.getAsyncData (function () {
that.specialfunction ();
that.anotherspecialfunction ();
});
}
};
myobj.render ();
이 예에서 MyOBJ 컨텍스트를 유지하려면 = this = this가 작동하는 변수를 유지하지만 function.prototype.bind ()를 사용하지 않고 깔끔하게 보이지 않습니다.
코드 사본은 다음과 같습니다.
렌더 : function () {
this.getAsyncData (function () {
this.specialFunction ();
this.anotherspecialfunction ();
} .bind (this));
}
.bind ()를 호출 할 때 단순히 새 함수를 생성 하고이 기능으로 전달합니다. .bind ()를 구현하는 코드는 다음과 같습니다.
다음과 같이 코드를 복사하십시오 : function.prototype.bind = function (scope) {
var fn = 이것;
return function () {
fn.apply (범위)를 반환합니다.
};
}
다음은 function.prototype.bind ()를 사용하는 간단한 예입니다.
코드 사본은 다음과 같습니다.
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+, Firefox 4.0+, IE 9+, Opera 11.60+, Safari 5.1.4+가 포함됩니다. IE 8/7/6 및 기타 브라우저는이를 지원하지 않지만 Mozilla Development Group은 이전 버전의 IE 브라우저와 유사한 기능을 갖춘 기능을 다음과 같이 작성했습니다.
코드 사본은 다음과 같습니다.
if (! function.prototype.bind) {
function.prototype.bind = function (othis) {
if (이것을 입력! == "function") {
// ECMAScript 5 내부 iscallable 기능에 가장 가까운 것
새 typeerror를 던지십시오 ( "function.prototype.bind- 묶으려고하는 것은 호출 할 수 없습니다");
}
var aargs = array.prototype.slice.call (Arguments, 1),
ftobind = 이것,
fnop = function () {},
fbound = function () {
ftobind.Apply를 반환합니다 (이 인스턴스 FNOP && OTHIS
? 이것
: Othis,
aargs.concat (array.prototype.slice.call (arguments)));
};
fnop.prototype = this.prototype;
fbound.prototype = new fnop ();
반환 fbound;
};
}