Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I am (still) completely in love with the almighty jQuery, and I have my own growing library of utilities that I want to codify in a java-script object. And I would like to keep syntax similar to that of jquery for the sake of simplicity for my other front end devs. So I want something like this:

 foo(argument).method(argument);

I have been trying something like this:

var foo = function(str){
    this.str = str;
}

foo.prototype = {
    alertTest  :  function(additional){
         alert(this.str + ' ' + additional);
    }
}

So that foo('hello').alertTest('world); with alert 'hello world'

I know this is possible, but I am not an OO guy and need help getting this simple thing right. Please help. I also intend on having many foo().bar(); type functions, like foo().somethingelse(); and foo().anotherthing(); . I have made several attempts, but am struggling hard here. Also there must be an awesome tight way of doing it.

Thanks folks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
281 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are almost there:

new foo('hello').alertTest('world');

or if you don't like the new:

var bar = function bar(str) {
    this.str = str;    
};

bar.prototype = {
    alertTest :  function(additional){
        alert(this.str + ' ' + additional);
        return this;
    }
};

function foo(str) {
    return new bar(str);
}

foo('hello').alertTest('world');

Live Demo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...