关于JavaScript对象属性的问题
对于以下简单构造函数:关于JavaScript对象属性的问题,javascript,Javascript,对于以下简单构造函数: const test = function(Num){ this.prop1 = Num + 1; this.prop2 = function(Num){ return 4 * Num; } }; let x = new test(5); console.log(x.prop2); console.log给出的是pro
const test = function(Num){
this.prop1 = Num + 1;
this.prop2 = function(Num){
return 4 * Num;
}
};
let x = new test(5);
console.log(x.prop2);
console.log给出的是prop2的确切内容,而不是4*Num的结果20。现在我似乎希望这样,但我不明白为什么。非常感谢您的帮助
console.log(x.prop2);
这只返回存储在变量prop2上的内容,不一定执行内部函数这个概念在js中称为函数闭包
NB:函数仅在后跟()时执行。如果在设置
测试(5)
时您的要求是prop2 print 20,则需要使用以下概念:
const test = function(Num){
this.prop1 = Num + 1;
this.prop2 = 4 * Num;
};
x.prop2
是一个函数,因此应该这样调用它:console.log(x.prop2())
因为prop2
是一个函数,您不调用该函数,只引用它。函数(Num)
中的Num
是该函数的参数,而不是函数(Num)
中的Num
。要使用@ManasKhandelwal注释,请尝试x.prop2(5)
或x.prop2(10)
。在最后一行调用itThus时,您需要指定一个参数。log(x.prop2())prop2
是函数引用,而不是“函数闭包”。函数中也没有(有用的)闭包,因为它的Num
param隐藏了外部Num
console.log(x.prop2())
将记录NaN
,因为它没有收到预期的参数。