2013-02-01 21 views
1

一直在讀我最喜歡的程序員之一Douglas Crockford,特別是'方法'方法。用Javascript鏈接,爲什麼它在這段代碼中很有用?

的JavaScript:

Function.prototype.method = function (name, func) { 
    this.prototype[name] = func; 
    return this; 
}; 
function myfunc(value) { 
this.value=value; 
} 

myfunc.method('toString', function() { 
    return this.value; 
}); 

var testvar = new myfunc('myself').toString(); 
alert(testvar); 

我感到困惑關於return this
return this這是什麼意思?
該方法沒有它,在我讀過的所謂的鏈接中,但我怎樣才能使用這個'方法'函數使用鏈接,爲什麼它有用?

謝謝

回答

4

從我的理解。
當您想要向正在擴展的函數(您使用的對象)添加的不僅僅是一個原型時,更改機制很有用。
請參見下面爲您例如擴大:

Function.prototype.method = function(name, func) 
{ 
    this.prototype[name] = func; 
    return this; 
}; 
function myfunc(value) 
{ 
    this.value = value; 
} 

myfunc 
    .method('toString',  function() {return this.value;}) 
    .method('toStringMore', function() {return this.value + ' more';}) 
    .method('bothFuncs', function() {return this.toString() + ' ' + this.toStringMore();}); 

var testvar = new myfunc('myself'); 

alert(testvar.toString()); 
alert(testvar.toStringMore()); 
alert(testvar.bothFuncs()); 

通過以上如果return this被排除在外,那麼結果是,第二和第三個電話給「方法」功能將失敗。
此外,請看直到鏈的末尾都沒有分號。

希望幫助

+0

哦不對所以這就是爲什麼它的有用的,這就是如何落實到我的代碼。非常感激 –

相關問題