javascript - 如何在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;
}
}
解决方案
您也可以使用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);
推荐阅读
- javascript - 我如何检查
使用类元素为空?
- cmake - 是否有一个 cmake 选项来指定源二进制目录?
- javascript - 添加其他选项的隐藏输入字段的值
- python - Matlab 和 Python 中用于矩阵乘法和求幂的不同结果
- c++ - 如何通过从用户那里获取 n 并成对生成数字来制作 n*n 矩阵的输出文件?
- javascript - 检查用户是否滚动超过一定数量
- python - IndexError:反转列表时列表索引超出范围错误
- javascript - 根据单击位置在行之间交换表格单元格
- javascript - Shopify:修改后购物车中的变体不正确
- excel - 在 Excel 中展开列表中的每个项目,并在第二个和第三个列表中包含所有变体