Javascript链规则,返回特定值而不是[Object object] [x]

xx3*_*004 6 javascript simulation return-value chain

问题出在标题上,但首先请看一下这段代码:

function number(a) {
    return {
        add: function(b) {
            result = a + b;
            return this;
        }, substract(b) {
            result = a - b;
            return this;
        }
}
Run Code Online (Sandbox Code Playgroud)

以上代码是链规则的简单示例.我重新调整了一个对象,所以我可以连续执行:

number(2).add(5).add(3 * 12).substract(Math.random());
Run Code Online (Sandbox Code Playgroud)

我的问题是,我必须重新调用一个对象以保持函数可链接.我想模仿链规则,但要返回具体的价值.例如,number(2).add(3)将返回5.

任何建议都非常感谢.

谢谢大家先进.[X]

小智 6

制作像5"可链接"这样的数值的一种方法是在适当的原型对象上定义一个方法,例如Number.prototype.例如:

Number.prototype.add = function (n) {
   return this + n
}

(5).add(2) // 7
5.0.add(2) // 7
5..add(2)  // 7
((5).add(2) + 1).add(34) // okay! 42
Run Code Online (Sandbox Code Playgroud)

上面的语法很有趣,因为它5.add(2)是无效的:JavaScript期待之后的数字(或"无")5..因为这是一个全局的副作用(它会影响所有数字),所以应该注意避免意外的交互.

唯一的另一个使"5"链能够的另一种方法是创建一个新Number对象(5不是真正的Number实例,即使它使用Number.prototype!)然后复制所需的方法.(我曾经认为这是唯一的另一种方式,但是请参阅KooiInc的答案 - 但是,我不确定从一个非字符串返回的定义是多么明确toString.)

function ops(a) {
  return {
    add: function(b) {
      var res = new Number(a + b) // important!
      var op = ops(res)
      res.add = op.add // copy over singletons
      return res
    }
  }
}
function number(a) {
  return ops(a)
}

number(5).add(2) + 1           // 8
(number(5).add(2) + 1).add(34) // error! add is not a function
Run Code Online (Sandbox Code Playgroud)

但是,请记住这会引入一些微妙的问题:

typeof 5                        // number
typeof new Number(5)            // object
5 instanceof Number             // false
new Number(5) instanceof Number // true
Run Code Online (Sandbox Code Playgroud)

这就是为什么我们需要一个Number(在JavaScript中搜索SO的"原语"):

x = 5
x.foo = "bar"
x.foo // undefined
Run Code Online (Sandbox Code Playgroud)

此外,结合cwolves的回答,考虑:

function number (n) { 
  if (this === window) { // or perhaps !(this instanceof number)
    return new number(n)
  } else {
    this.value = n
  }
}
Run Code Online (Sandbox Code Playgroud)

然后两者new number(2)number(2)将评估为一个新的数字对象.

number(2).value     // 2
new number(2).value // 2
number(2) instanceof number     // true
new number(2) instanceof number // true
Run Code Online (Sandbox Code Playgroud)

快乐的编码.


小智 3

你有两个选择。您可以返回新对象:

function number(a){
    return this instanceof number ? (this.value = a, this) : new number(a);
}

number.prototype = {
    valueOf : function(){
        return this.value;
    },
    add : function(b){
        return new number(this.val + b);
    },
    subtract : function(b){
        return new number(this.val - b);
    }
};
Run Code Online (Sandbox Code Playgroud)

或者你可以修改现有的(大部分与上面的代码相同,这是不同的):

add : function(b){
    this.value += b;
    return this;
},
Run Code Online (Sandbox Code Playgroud)

区别在于它们的行为方式:

var x = new number(5),
    y = x.add(10);

// with first example
// x == 5, y == 15


// with 2nd example
// x == 15, y == 15, x === y
Run Code Online (Sandbox Code Playgroud)