Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于JavaScript对象属性的问题_Javascript - Fatal编程技术网

关于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,则需要使用以下概念:

  • f(x)=x*4
  • x=5
  • f(5)=5*4=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
    ,因为它没有收到预期的参数。