[英]JS: how to create optionally chainable methods
JS新手問題在這里:
假設我有一些簡單的字符串操作方法,例如這些愚蠢的示例:
var prepend = function(str) {
return 'foo ' + str
};
var exclaim = function(str) {
return str + '!'
}
現在,我可以像這樣使用它們:
var string = prepend('bar'); // 'foo bar'
string = exclaim(string); // 'foo bar!'
但是,我認為,如果我還可以( 可選 )使這些方法可鏈接,那真的很整潔,因此我還可以執行以下操作:
var string = "foo"
string.prepend().exclaim()
...而我仍然會得到"foo bar!"
作為我的結果。
如果我還可以將可選的args傳遞到此鏈中,那就更好了,例如:
var exclaim = function(string,char="!") {
return string + char
};
因此,我的問題是:
很基本,但是我能正確描述嗎? 您如何稱呼可以像這樣鏈接的方法? 而且,您將鏈中上一個方法的返回稱為什么,該下一個方法將要執行的操作呢?
如何將變量設置為鏈中上一個方法的返回值,還是作為參數提供?
謝謝!
如果要鏈接它們,則必須將這些方法添加到字符串原型中:
String.prototype.prepend = function() {
return 'foo ' + this
};
String.prototype.exclaim = function() {
return this + '!'
}
var s = "".prepend().exclaim();
console.log(s);
在WRT可選參數中,您可以利用以下事實:在JavaScript中,您可以調用方法而無需傳遞某些參數的值。 這些未傳遞的參數將在函數中顯示為undefined
。 由於null
隱式轉換為undefined
,通常可以通過檢查這些參數是否為null來處理
var exclaim = function(str, ch) {
if (ch == null){
ch = '!';
}
return string + ch
};
您還會經常看到如下所示的內容:
var exclaim = function(str, ch) {
ch = ch || '!';
return string + ch
};
相似,但是將覆蓋6個“ falsy”值中的任何一個: null
, undefined
, NaN
, 0
, false
和''
(空字符串)。 因此,如果您要這樣做,並嘗試在ch中傳遞一個空字符串,它將被覆蓋。
要使用可鏈接方法,您應該返回包含該方法的對象的實例。 在大多數情況下,您將退還this
款項。
例如,請參MyString
類
function MyString(s){
this.str = s;
}
MyString.prototype.lower=function(){
this.str = this.str.toLowerCase();
return this;
}
MyString.prototype.upper=function(){
this.str = this.str.toUpperCase();
return this;
}
MyString.prototype.last=function(x){
return this.str.substr(-x);
}
MyString.prototype.first=function(x){
return this.str.substr(0,x);
}
MyString.prototype.get=function(){
return this.str;
}
var ms = new MyString("Hello");
var s = ms.lower().first(2); // s = 'he';
您可以這樣做:
var string = exclaim(prepend('bar'));
或者,您可以擴展String對象,以便可以使用.prepend()和.exclaim()語法:
String.prototype.prepend = function() {
return 'foo ' + this
};
String.prototype.exclaim = function() {
return this + '!'
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.