JavaScript 链式方法困境

JavaScript Chainable Method Delimma

我有 2 个方法想用作可链接的方法。可以链接其他方法以进一步修改文本。

left returns 从左边算起 X 个字符。 右边 returns 从右边开始 X 个字符。

目前我可以做到:

var txt = "hello";
S$(txt).left(4).right(2).val //returns "ll"

我想做的就是这个。 基本上我想 return 最后一个链接方法之后的结果,而不必调用 属性。这可能吗?

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));

您可以覆盖 valueOftoString Object 的方法来实现它。

示例:

var myObject = {
    value: 5,
    valueOf: function(){
        return this.value;
    },
    toString: function() {
        return 'value of this object is' + this.value;
    }
};

由于 Javascript 是一个 duck typing language,没有什么会阻止您执行 数学运算 字符串连接 反对 原始 values/objects 因为这些方法在表达式评估过程中被调用,无论它们来自哪里。

示例:

console.log(myObject + 10); 将打印 15

alert(myObject); 将打印 'value of this object is 5'