首页 > 解决方案 > 如何在js中创建对象链

问题描述

我在面试中被要求解决

init(1).add(2).mul(3).div(4).val();

输出它应该实现这个功能,我比较关心如何用上面的方式调用

(1 + 2) * 3 / 4 = 2.25

我们如何使用 javascript 来实现它?我想用嵌套函数创建函数,正确的方法是什么?

我做了

var gmap = function(num) {
this.x = num;

this.add = function(ad) {
    this.x = this.x * ad;
    return this;
}

this.del = function(de) {
   this.x = this.x + de;
   return this;
}

this.final = function() {
    return this.x;
}

}

标签: javascript

解决方案


您也可以使用class样式来做到这一点

class Chainable{

    init(num){
        this.total = num;
        return this;
    }

    add(num){
        this.total += num;
        return this;
    }
}

像这样使用它

var c = new Chainable();
c.init(1).add(1);

推荐阅读