[英]How do I make my function anonymous in JavaScript?
In the code below I firstly try to print the 'normal' way. 在下面的代码中,我首先尝试打印“正常”方式。 Secondly I try to anonymize my function and assign it to a variable which I then print.
其次,我尝试使函数匿名化,并将其分配给一个变量,然后将其打印出来。 In Chrome this now proceeds to print the source code.
在Chrome中,现在可以继续打印源代码。 What am I doing wrong?
我究竟做错了什么?
function sumSq() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
console.log(sumSq());
var mySum = function() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
console.log(mySum);
Function should be called as mySum()
函数应称为
mySum()
Apart from this, both ways do the same. 除此之外,这两种方法都做同样的事情。
Call mySum
using ()
: 使用
()
调用mySum
:
console.log(mySum());
Functions are objects, so when you call 函数是对象,所以当您调用
console.log(mySum);
JS calls toString on the mySum object (which mySum inherits from the Object prototype). JS在mySum对象(mySum从Object原型继承的对象)上调用toString。 That's why the source gets printed.
这就是来源被打印的原因。
var mySum = function() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
is just the same with: 与以下内容相同:
function mySum() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
And call it console.log(mySum());
并命名为
console.log(mySum());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.