2

I was reading through fluent api I got a doubt.

I want to take in a string upon which a jQuery function or example is called upon

Function

function compareThis(newString) {
    function compare(newString) {
        if (this == newString) {
            alert("same string");
        } else {
            alert("differnt string");
        }
    }
}

Where it is called as

("alerting").compareThis("alerted").compare();  //alert 'different string'

I want to pass the data/string not as parameter but as called upon.

JSFiddle

Note: I would like to call the function in similar cases like finding date interval etc

2 Answers 2

4

You can use prototype to add function to String class:

String.prototype.compare = function(newString){
    if (this == newString) {
       alert("same string");
    } else {
        alert("differnt string");
    }
};

I think you should adapt the code for your function, but it's the idea.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, if you use Date instead of date ;)
Really you should do if (this.valueOf() === newString) {
@Getz How may I include this in a widget? I tried to use this function in a widget but failed.
1

Maybe I missed interpreted however, it looks as it you required a form of method chaining to compare string. To do this you can create a variable and create functions inside it.

var compare = (function(){

    var thisString;
    var stringToCompare;

    var create = function(sVal) {
        thisString = sVal;
        return this;
    };

    // Public
    var compareThis = function(sVal) {
        stringToCompare = sVal;
        return this;
    };

    var compare = function(anotherString) {
        return thisString == stringToCompare;
    };

    return {
        create: create,
        compareThis: compareThis,
        compare: compare
    };

}());

var b = compare.create('test').compareThis('test').compare();
alert(b);

Example fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.