JavaScript Delimma Chain Method

I have 2 methods that I would like to use as a chain. Other methods may be encoded to further modify the text.

left returns the X characters on the left. on the right returns the X characters on the right.

Currently I can do this:

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

I want to do this. Basically I want to return the results after the last chaining method without having to call the property. Is it possible?

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

Below is the main code:

(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));
Run codeHide result
+4
source share
1 answer

You can override methods valueOfand toString Objectarchiving.

Example:

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

Javascript , string /, , .

:

console.log(myObject + 10);   15

alert(myObject);   ' 5'

+6

Source: https://habr.com/ru/post/1622822/


All Articles