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

How to implement chained method calls like jQuery?

本文关键字:一样 调用 方法 jQuery 何实现 实现      更新时间:2023-09-26

所以我(仍然)完全爱上了强大的jQuery,并且我有自己的不断增长的实用程序库,我想将其编写在java-script对象中。为了其他前端开发人员的简单性,我希望保持与jquery相似的语法。所以我想要这样写:

 foo(argument).method(argument);

我一直在尝试这样做:

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

foo('hello').alertTest('world ');提示"hello world"

我知道这是可能的,但我不是一个OO的家伙,需要帮助得到这个简单的事情正确。请帮助。我还打算有许多foo().bar();类型函数,如foo().somethingelse();和foo () .anotherthing ();. 我做了几次尝试,但在这里很挣扎。而且必须有一个非常紧凑的方法来做到这一点。

谢谢大家!

你就快成功了:

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

现场演示。

我之前做过这样的事情,这是一个非常有趣的创建!

如果我没记错的话,为了能够使用点操作符,我必须返回对象作为原始函数调用的一部分。这样我就可以把很多东西连在一起比如$(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/

我做得很快,但你可以联系到我们在这里试图实现的本质-

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

现在回答这个问题已经太晚了,而且jquery已经被弃用了。但是人们还是经常被问到这个问题。

我将实现如下而不使用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();