简体   繁体   English

为什么这个javascript装饰功能不起作用?

[英]why this javascript decorate function doesn't work?

I am looking at decorate function. 我在看装饰功能。 For example, decorate function can make sum() function to return a double sum. 例如,decorate函数可以使sum()函数返回一个双精度和。 But the following code doesn't work as desired, I changed the 'f' to 'sum', please see comment on relevant line, why I cannot change this? 但是以下代码无法正常工作,我将“ f”更改为“ sum”,请参见相关行的注释,为什么我不能更改此代码?

<script>
function doublingDecorator(f) {        

  return function() {

    return 2*sum.apply(this, arguments); // the original code is: return 2*f.apply(this,arguments) I changed to sum, then doesn't work.
  } 
}

// Usage:

function sum(a, b) {
  return a + b
}


var sum =  doublingDecorator(sum);          // sum gets decoration


alert (sum(3,4)); //return 14
</script>

f in doublingDecorator is not used. 不使用doublingDecorator f Instead you reference sum , which you also redefine. 相反,您引用sum ,您也重新定义了它。 This causes an infinite loop. 这将导致无限循环。

function doublingDecorator(f) {        
  return function() {
    return 2*f.apply(this, arguments);
          // ^-- f instead of sum!
  } 
}
function sum(a, b) {
  return a + b
}
var sum = doublingDecorator(sum); // note: sum is already declared here, redeclaring is technically wrong.
console.log(sum (3,4)); // 14

Two things: 两件事情:

  • You changed the inner f.apply to sum.apply . 您将内部f.apply更改为sum.apply
  • You redefine sum . 您重新定义sum

That's why it's breaking. 这就是为什么它破了。 Your change makes it a recursive call that never ends (infinite recursion) because sum calls itself over and over again. 您的更改使它成为永无休止的递归调用(无限递归),因为sum一次又一次地调用自身。 This is because you reference sum inside, which you have also redefined. 这是因为您在内部引用了sum ,您也重新定义了sum

Eventually the recursion ends up exceeding the maximum call-stack size. 最终,递归最终超出了最大调用堆栈大小。

I recommend leaving f.apply as it is. 我建议保持f.apply Then your code should work. 然后您的代码应该工作了。 Another option is to not redefine sum . 另一种选择是不重新定义sum So do this instead: 因此改为:

var newSum = doublingOperator(sum);
console.log(newSum(3, 4)); //returns 14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM