有關JavaScript中的prototype.bind()方法介紹
以前,你可能會直接設置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;
};
}
-
javascript中的return和閉包函數
複製代碼代碼如下:functionmakefunc(x){returnfunction(){returnx;}}alert(makefunc(0));其實不是不執行,只是朋友的意思這裏alert出來的`應該是“0”,而不是function(){returnx;}。不是腳本寫錯了,只是沒搞懂return,從當前函數退出,並從那個函數返回一個值。如果返...
-
Dreamweaver技巧詳解
Dreamweaver由MX版本開始使用Opera軟件公司的排版引擎“Presto”作為網頁預覽。下面給大家介紹Dreamweaver技巧,一起來學習吧!Dreamweaver技巧詳解1、靈活運用樣式熟悉網頁設計的網友就知道,調用Style的方法很多,我們可以單擊鼠標右鍵選擇CustonStyle來調用Style...
-
SQL的SUBSTR 函數的使用方法介紹
SUBSTR函數是用來截取數據庫某一列字段中的一部分。在各個數據庫的函數名稱不一樣(真是蛋疼,後發明的`數據庫難道不能同先發明的一樣嗎?)複製代碼代碼如下:MySQL:SUBSTR(),SUBSTRING()Oracle:SUBSTR()SQLServer:SUBSTRING();常用的方式是:SBUSTR(str,pos);就是從pos...
-
如何理解Javascript的caller,callee,call,apply區別
在提到上述的概念之前,首先想説説javascript中函數的隱含參數:argumentsarguments該對象代表正在執行的函數和調用它的函數的參數。[function.]arguments[n]參數function:選項。當前正在執行的Function對象的名字。n:選項。要傳遞給Function對象的從0開始的參數值...
相關文章
- My Happy Times During Winter Vacation國中英語作文
- Thinkpad筆記本開機顯示Tointerrruptnormalstartup解決方法
- JavaScript在Android的WebView中parseInt函數轉換不正確
- 關於JavaScript中isPrototypeOf函數作用和使用實例
- JavaScript toFixed方法介紹
- Time To Stop Worrying About Invasive Species美文欣賞
- The relationship between theory and practice大學英語作文
- JavaScript中的原型鏈prototype詳解
- 國中英語寫作範文:My Happy Times During Winter Vacation
- 英語閲讀:VIT declines to acquire Ang Mo Kio property