【问题标题】:Why is closure property not working in nodejs?为什么闭包属性在nodejs中不起作用?
【发布时间】:2020-12-29 04:52:48
【问题描述】:

我是 node js 的新手,正在学习它的课程。但是,我无法在其中使用 javascript 的简单闭包属性。我有 2 个文件 index.js 和 rectangle.js,其中我使用回调来返回矩形的面积和周长。

index.js

var rect = require('./rectangle');

function solveRect(l,b) {
    console.log("Solving for rectangle with l = " + l + "and b = " + b);

    rect(l,b, (err,rectangle) => {
        if(err) {
            console.log("ERROR: " + err.message);
        }
        else {
            console.log("The area of rectangle of dimensions l = " 
                + l + "and b = " + b + " is "  + rectangle.area());

            console.log("The perimeter of rectangle of dimensions l = " 
                + l + "and b = " + b + " is "  + rectangle.perimeter());
        }
    });
    console.log("This statement is after the call to rect()");
}

solveRect(2,4);
solveRect(3,5);
solveRect(0,4);
solveRect(-3,-5);

rectangle.js

module.exports = (x,y,callback) => {
    if( x <= 0 || y <= 0) {
        setTimeout(() =>
            callback(new Error("rectangle dimensions should be greater than zero"),
                null),
            2000
        );
    }
    else {
        setTimeout(() =>
            callback(null,
                {
                    perimeter: (x,y) => (2*(x+y)),
                    area: (x,y) => (x*y)
                }),
            2000
        );
    }
}

我看到由于外部范围的回调已经可以使用长度和宽度,所以当我们调用 rectangle.area() 函数时不需要传递它们。

输出:我得到 NaN 作为面积和周长返回,而不是实际计算的面积。

【问题讨论】:

    标签: javascript node.js closures


    【解决方案1】:

    perimiterarea 函数接受参数 xy,因此它们使用这些参数来计算结果,而不是从闭包继承的变量。由于在 solveRect() 中调用它们时没有提供任何参数,因此您正在对 undefined 执行算术运算,结果为 NaN

    去掉参数,以便它们使用闭包变量。

            setTimeout(() =>
                callback(null,
                    {
                        perimeter: () => (2*(x+y)),
                        area: () => (x*y)
                    }),
                2000
            );
    

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 2019-02-19
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多