有人问我,在接受采访时解决
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;
}
}
您可以使用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);
你可以做这样的事情使用builder pattern(ES6):
function init(value) {
this.result = value;
return {
add: function(addValue) {
this.result = this.result + addValue;
return this;
},
mul: function(mulValue) {
this.result = this.result * mulValue;
return this;
},
div: function(divValue) {
this.result = this.result / divValue
return this;
},
val: function() {
return this.result;
},
result: this.result,
};
}
init(1).add(2).mul(3).div(4).result
如果你不希望使用一个类的实例,你可以使用闭包:
function init(start) {
// this is the starting value that will get updated with each function call
let value = start;
// This is the object to be returned, notice that seach return the object instance
let self = {
add: num => {
value += num;
return self;
},
sub: num => {
value -= num;
return self;
},
mul: num => {
value *= num;
return self;
},
div: num => {
value /= num;
return self;
},
val: () => {
return value;
}
};
return self;
}
init(1).add(2).mul(3).div(4).val(); // 2.25
从本质上讲,每次调用init函数创建一个新的闭合范围。在此范围内,所创建的,只有在该范围内访问的任何局部变量的新实例。
当init函数被调用时,两个新的变量实例被创建value
和self
那些仅仅在init函数创建的其他“东西”访问。
随着每这些功能,我们返回一个包含函数集是如何的能够链调用该变量。