关于javascript函数valueOf\toString和“curry”函数在Chrome、Firefox和node环境中的行为不同
我写了一个函数:关于javascript函数valueOf\toString和“curry”函数在Chrome、Firefox和node环境中的行为不同,javascript,node.js,google-chrome,firefox,Javascript,Node.js,Google Chrome,Firefox,我写了一个函数: function add(){ let arr = []; arr = arr.concat(Array.prototype.slice.apply(arguments)) let fun = function(){ arr = arr.concat(Array.prototype.slice.apply(arguments)) return fun } fun.toString = function(){
function add(){
let arr = [];
arr = arr.concat(Array.prototype.slice.apply(arguments))
let fun = function(){
arr = arr.concat(Array.prototype.slice.apply(arguments))
return fun
}
fun.toString = function(){
console.log(222)
return arr.reduce(function(total, num){
return total+num
}, 0)
}
return fun
}
console.log(add(1,2)(2,3)(3))
这是镀铬的:
两个问题:
在第一行,为什么“f 11”不是“11”
为什么先输出'f 11'而不是'222',我认为应该先执行类型转换,然后在控制台上输出计算结果
另一件奇怪的事情是,Firefox中的代码相同:
以及节点环境中的结果:
我不明白,在FF和node中,为什么没有执行计算的操作
请帮帮我…非常感谢 首先,您可以稍微美化一下整个代码:
function add(..arr){
function fun(...args){
arr.push(...args);
return fun
}
fun.toString = function(){
return arr.reduce((total, num) => total + num)
};
return fun;
}
正如您正确注意到的,记录函数完全取决于环境。Firefox和Node返回函数的代码,而Chrome则执行以下操作:
out( "f" + add.toString())
所以我们的toString函数被调用,并记录了一些东西。为了在不同的环境之间保持一致的行为,我们可以显式地调用toString:
console.log(add(1)(2)(3).toString());
这可以推断:
console.log("" + add(1)(2));
如果您想添加的是可变和咖喱,我仍然认为这很奇怪,只需执行以下操作:
const add = (...args) => {
let accum = args;
let f = (...fargs) => {
if (!fargs.length) {
return accum.reduce((a, b) => { return a + b; }, 0);
} else {
accum = accum.concat(fargs);
return f;
}
};
return f;
};
add(1,2,3)(); // 6
add(1)(2,3)(); // 6
add()(); // 0
现在,您只需调用返回的函数,而不使用任何参数来获取值。你可以玩弄它来提高性能,例如,使用.push而不是.concat循环,但这应该可以工作。f表示正确的函数这有什么意义?为什么要调用toString来获取值?这完全违反直觉。试图同时拥有一个可变和咖喱的加法函数是……奇怪的。@JonasW。正确的函数?@JaredSmith我同意你的看法。这是别人问我的问题。如果我这样做,我想应该是这样的:add12.getValue…但是这个问题不允许“getValue”,所以我必须调用toString或valueOf来获取值。@JonasW。我明白了,就像这样:var-app=function{};app.toString=函数{return 11};函数app1{return app};console.logapp1.Chrome返回'f11',FF和节点返回函数'app'。仅在Chrone app.toString上被调用…是的,没错。这可能是一个很好的解决方案。但我想知道为什么会输出一个函数,而不是一个值,在FF或node中,'console.log222'似乎不会被执行…@daXiong Firefox和node返回函数的代码,而Chrome会这样做:…或accum.push…Fargsu。我知道了。这是个好主意!