假设我需要像这样创建一个JavaScript库:

;(function(){

    var root = this;

    var Ctor = function(value) {
        this.value = value;
    };

    var _ = new Ctor(value);

    _.doSome = function(value) {
        // do some work to the value
        // if no value assigned, get the value of the previous method
    };

   _.doSome2 = function(value) {
        // do some work to the value
        // if no value assigned, get the value of the previous method
    };

   _.doSome3 = function(value) {
        // do some work to the value
        // if no value assigned, get the value of the previous method
    };

   root._ = _;

}.call(this));


如果doSome方法起作用了_对象的值,则doSome2和doSome3也起作用。

但是如何像这样链接方法:

// the doSome2 and doSome3 work with the value of doSome
_.doSome(value).doSome2().doSome3();

// the doSome3 work with the value of doSome2 cuz it has a value
_.doSome(value).doSome2(value).doSome3();

// every method work with the value assigned to it
_.doSome(value).doSome2(value).doSome3(value); // the same as:
_.doSome(value);
_.doSome2(value);
_.doSome3(value);


注意:方法可以随机链接,例如:

_.doSome2(value).doSome().doSome3();


实时示例:https://jsbin.com/vijehotora/edit?js,console

最佳答案

您可以执行以下操作:

var Ctor = function() {};

Ctor.prototype = {
    doSome: function(value) {
        if(value) {
            this.value = value;
        }

        return this;
    },

    doSome2: function(value) {
        if(value) {
            this.value = value;
        }

        return this;
    }
};

new Ctor().doSome('value1').doSome2('value2').doSome();


Working example

10-02 04:15