Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Chainable Method Delimma

I have 2 methods that I'd like to use as chainable methods. Other methods may be chained to further modify text.

left returns X characters from the left. right returns X characters from the right.

Currently I can do this:

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

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

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

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));
like image 220
Chicago Excel User Avatar asked Jan 04 '16 21:01

Chicago Excel User


1 Answers

You can override valueOf and toString methods of Object to archieve it.

Example:

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

As Javascript is a duck typing language, nothing will prevent you from performing mathematical operations and string concatenation against primitive values/objects as these methods are called during expression evaluation process no matter where they came from.

Examples:

console.log(myObject + 10); will print 15

alert(myObject); will print 'value of this object is 5'

like image 136
Cleiton Avatar answered Oct 20 '22 00:10

Cleiton