理解Javascript代码片段
我的教授给了我们以下Javascript片段,我们应该对其进行分析:理解Javascript代码片段,javascript,Javascript,我的教授给了我们以下Javascript片段,我们应该对其进行分析: function createMultiplyer(multiple) { n = multiple; return function(num) { return num * n; }; } var fiveMultiplyer = createMultiplyer(15); var x = fiveMultiplyer(10); alert(x); alert(fiveMultiplyer); 这段代码输出一个包含文
function createMultiplyer(multiple) {
n = multiple;
return function(num) {
return num * n;
};
}
var fiveMultiplyer = createMultiplyer(15);
var x = fiveMultiplyer(10);
alert(x);
alert(fiveMultiplyer);
这段代码输出一个包含文本“150”的警报,后面是另一个警报,其内容为function(num){return num*n;}
。然而,我似乎无法理解为什么会这样
有人能帮我追踪代码并解释发生了什么吗
var fiveMultiplyer = createMultiplyer(15); // Create a function that multiplies with 15
此函数在本地称为fiveMultiplier
var x = fiveMultiplyer(10); // Invoke the multiply-by-15 with argument 10
结果在本地称为x
alert(x); // 150
alert(fiveMultiplyer); // The definition of multiply-by-15 as
// it is returned from createMultiplyer
在JavaScript中,也可以使用一个变量作为函数
var fiveMultiplyer = createMultiplyer(15);
You are calling a CreateMultiplyer(15) function.
This function returns you another function and that is associated
with the fiveMultiplyer var.
var x = fiveMultiplyer(10);
You are actually invoking the function which was returned in previous step.
hence evaluating the value to 10 * 15 = 150
alert(x);
As explained this returns 150
alert(fiveMultiplyer);
As explained this returns the complete function
returned by createMultiplyer().
<强> 1 < /强>让我们考虑线
var fiveMultiplyer = createMultiplyer(15);
之后,fiveMultiplyer
变量的返回值为createMultiplyer
函数(函数就是这样工作的)。这个返回值是
function(num) {
return num * n;
};
因此,代码与此类似(关于n
稍后)
2下一行是
var x = fiveMultiplyer(10);
这里我们只调用上面的函数。它还使用变量n
:该变量在createMultiplyer
函数中设置:n=multiple代码>。因此,在我们的例子中,n
是15
,fiveMultiplyer(10)
相当于10*15
就这些。希望能有帮助
编辑
我还要注意,n
是一个全局变量,它的声明方式是这样的。因此,您可以从代码中的任何位置访问它。最好将其视为类或对象。var fiveMultiplyer正在创建一个对象,该对象包含一个值n=15,并具有一个函数,该函数接受一个数字并将其乘以n
在Java中,这看起来像这样
public class Multiplyer {
private int n;
public Multiplyer(int n) {
this->n = n;
}
public int multiple (int m) {
return n*m;
}
}
Multiplyer myMultiplyer = new Multiplyer(15);
System.out.println( myMultiplyer.multiple(10) );
然而,在JavaScript中,变量fiveMultiplye不必调用其方法,只需向其传递所需的变量,它就会调用方法并为您返回
希望有帮助
var x = fiveMultiplyer(10);
public class Multiplyer {
private int n;
public Multiplyer(int n) {
this->n = n;
}
public int multiple (int m) {
return n*m;
}
}
Multiplyer myMultiplyer = new Multiplyer(15);
System.out.println( myMultiplyer.multiple(10) );