如何实现像jQuery这样的链式方法调用?

时间:2011-09-08 21:31:46

标签: javascript object

所以我(仍然)完全爱上了全能的jQuery,我有自己不断增长的实用程序库,我想在java脚本对象中编写代码。为了简化我的其他前端开发人员,我想保持类似于jquery的语法。所以我想要这样的东西:

 foo(argument).method(argument);

我一直在尝试这样的事情:

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

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

这就是foo('你好')。alertTest('world);提醒'你好世界'

我知道这是可能的,但我不是一个OO人,需要帮助才能让这件事变得简单。请帮忙。我还打算有很多foo()。bar();类型函数,如foo()。somethingelse();和foo()。anotherthing(); 。我做了几次尝试,但我在这里努力奋斗。还必须有一种非常紧凑的方法。

谢谢大家!

4 个答案:

答案 0 :(得分:5)

你快到了:

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

或者如果您不喜欢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

答案 1 :(得分:2)

我刚才做了类似的事情,创造了很多乐趣!

如果我没记错的话,为了能够使用点运算符,我必须将对象作为原始函数调用的一部分返回。通过这种方式,我可以像$(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"

如果有助于参考:http://www.mikedoesweb.com/vis/

答案 2 :(得分:1)

我做得很快的事情,但你可以与我们在这里想要实现的目标有关 -

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();

答案 3 :(得分:0)

回答这个问题已经很晚了,jQuery也已被弃用。但是仍然有人经常问这个问题。

我将在不使用原型的情况下像下面那样实现-

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();

相关问题