最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to implement chained method calls like jQuery? - Stack Overflow

programmeradmin6浏览0评论

So I am (still) pletely 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!

So I am (still) pletely 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!

Share Improve this question edited Sep 8, 2011 at 21:50 user166390 asked Sep 8, 2011 at 21:31 FresheyeballFresheyeball 30.1k21 gold badges105 silver badges167 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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.

I did something like this a while ago and it was a ton of fun to create!

If i remember correctly, To be able to use dot-operators, I had to return the object as part of the original function call. This way I could chain lots of stuff together like $(id).value('asdf').color('#ff0000')

function $(id){
    this.e = document.getelementbyid(id)
    me = this
    this.val = function (newval) {
        this.e.value = newval;
        return me;  // <- Important
    };
    return this;  //  <- Important
}

$("textbox1").val("New Value")    // changes textbox1's value to "New Value"

If it helps for reference: http://www.mikedoesweb./vis/

Something I did really quick but you can relate to the essence of what we are trying to achieve here -

function ChainingObj() {
  if (!(this instanceof ChainingObj)) {
    return new ChainingObj();
  }
}

ChainingObj.prototype.first = function() {
  console.log("foo");
  return this; //important to return this.
}


ChainingObj.prototype.second = function() {
  console.log("bar");
  return this;
}

var a = ChainingObj().first().second();

It is quite late to answer this question and also jquery is quite deprecated. But still people get asked this question quite frequently.

I would implement like below without using prototype -

const wrapper = (person) => ({
    sayGoodMorning:() => {
        console.log("Good Morning, "+person.name)
        return wrapper(person);
    },
    showAlert:() => {
       alert("Hey I am alert");
       return wrapper(person);
    },
    sayGoodEvening:() => {
        console.log("Good Evening, " + person.name)
        return wrapper(person);
    },
    sayGoodNight:() => {
        console.log("Good Night, " + person.name)
        return wrapper(person);
    },
  });
  const person = {name:"StackOverflow"};
  const $ = (obj) => wrapper(obj);
  const $example = $(person);
  
  $example
    .showAlert()
    .sayGoodMorning()
    .sayGoodEvening()
    .sayGoodNight();

发布评论

评论列表(0)

  1. 暂无评论