有關JavaScript中的prototype.bind()方法介紹
- 網頁設計
- 關注:3.07W次
以前,你可能會直接設置self=this或者that=this等等,這樣做當然也能起作用,但是使用()會更好,看上去也更專業。
下面舉個簡單的例子:
複製代碼 代碼如下:
var myObj = {
specialFunction: function () {
},
anotherSpecialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
var that = this;
syncData(function () {
ialFunction();
herSpecialFunction();
});
}
};
er();
在這個例子中,為了保持myObj上下文,設置了一個變量that=this,這樣是可行的,但是沒有使用()看着更整潔:
複製代碼 代碼如下:
render: function () {
syncData(function () {
ialFunction();
herSpecialFunction();
}(this));
}
在調用()時,它會簡單的創建一個新的函數,然後把this傳給這個函數。實現()的代碼大概是這樣的:
複製代碼 代碼如下: = function (scope) {
var fn = this;
return function () {
return y(scope);
};
}
下面在看一個簡單的使用()的.例子:
複製代碼 代碼如下:
var foo = {
x: 3
};
var bar = function(){
(this.x);
};
bar(); // undefined
var boundFunc = (foo);
boundFunc(); // 3
是不是很好用呢!不過遺憾的是IE8及以下的IE瀏覽器並不支持()。支持的瀏覽器有Chrome 7+,Firefox 4.0+,IE 9+,Opera 11.60+,Safari 5.1.4+。雖然IE 8/7/6等瀏覽器不支持,但是Mozilla開發組為老版本的IE瀏覽器寫了一個功能類似的函數,代碼如下:
複製代碼 代碼如下:
if (!) {
= function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError(" - what is trying to be bound is not callable");
}
var aArgs = (arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return y(this instanceof fNOP && oThis
? this
: oThis,
at((arguments)));
};
otype = otype;
otype = new fNOP();
return fBound;
};
}
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-hk/sjzz/sjzz/xowdqn.html