![](/img/trans.png)
[英]Do JavaScript arrays have a chainable method similar to forEach?
[英]JavaScript Chainable Method Delimma
我有兩種方法可以用作可鏈式方法。 可以鏈接其他方法以進一步修改文本。
left從左側返回X個字符。 right從右邊返回X個字符。
目前我可以這樣做:
var txt = "hello"; S$(txt).left(4).right(2).val //returns "ll"
我想做的就是這個。 基本上我想在最后一個鏈式方法之后返回結果,而不必調用屬性。 這可能嗎?
var txt = "hello"; S$(txt).left(4).right(2) //returns "ll"
以下是主要代碼:
(function (global) { var jInit = function(text){ this.text = text; this.val = text; } var jIn = function(text){ return new jInit(text); } var jStringy = jStringy || jIn; jInit.prototype.left = function (num_char) { if (num_char == undefined) { throw "Number of characters is required!"; } this.val = this.val.substring(0, num_char); return this; } jInit.prototype.right = function (numchar) { this.val = this.val.substring(this.val.length - numchar, this.val.length); return this; } global.jStringy = global.S$ = jStringy; return this; }(window));
您可以覆蓋 Object
valueOf
和toString
方法來實現它。
例:
var myObject = {
value: 5,
valueOf: function(){
return this.value;
},
toString: function() {
return 'value of this object is' + this.value;
}
};
由於Javascript是一種鴨子打字語言 ,因此在表達式評估過程中無論它們來自哪里,都不會阻止您對原始值/對象執行數學運算和字符串連接 。
例子:
console.log(myObject + 10);
將打印15
alert(myObject);
將打印'此對象的值為5'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.