Return 链接后最后一个对象

Return an object at the end after chaining

我正在尝试创建一个流畅的模式,以便我可以将功能链接在一起。像下面这样的东西。但是我想 return 最后的对象。

var foo = new create();
foo.x("hello")
   .y("howdy!")
   .z("hello")
   .get_obj();

现在我似乎得到了一个 pointer/reference 到 create() 函数,这是因为我在每次函数调用后都是 return 这个(我猜?)。我知道我可以做类似 var bar = foo.obj; 的事情,但如果有办法避免这种情况,我将不胜感激。我是 Javascript 的新手,我以前使用过 Typescript,所以我的闭包知识有限,如果这是问题的话。

function create() {
    this.obj = {}

    this.x = function(value) {
        this.obj["key_x"] = value;
        return this;
    }

    this.y = function(value) {
        this.obj["key_y"] = value;
        return this;
    }

    this.z = function(name) {
        this.obj["key_z"] = value;
        return this;
    }

    this.get_obj = function() {
        return this.obj;
    }
}

您没有将链的结果分配给任何东西,因此 foo 保持不变,仍然是 new create() 的结果。

也许你的意思是这样做?

var foo = new create()
   .x("hello")
   .y("howdy!")
   .z("hello")
   .get_object();

那么foo应该就是你期望的对象了


很难从示例代码中判断出您的确切用例,但您可以像这样写一些更简洁的东西:

function Create();
Create.prototype = {
    x: function(value) {
        this["key_x"] = value;
        return this;
    },

    y: function(value) {
        this["key_y"] = value;
        return this;
    },

    z: function(value) {
        this["key_z"] = value;
        return this;
    }
}

var foo = new Create()
   .x("hello")
   .y("howdy!")
   .z("hello");