为什么当使用 'new' 创建对象并立即返回时,函数作为对象 属性 不访问闭包?

Why function as an object property not accessing the closure when object is created using 'new' and returned immediately?

现在我正在调用 data() 函数,它将创建一个局部变量 x 和 return 对象,该对象与 obj 函数和 new 关键字一起创建,其中有 属性 fun 其值是另一个 function.Then 为什么 returned fun 方法不访问闭包 x?

var obj=function(){
    this.fun=function(){
        console.log(x);
    };
};

var data=function(){
    var x=5;
    return new obj();
};

var y=data();
y.fun();

现在我们不再创建新对象,而是放置相同的对象并 return 它。 现在它可以访问闭包 x。为什么?

var data=function(){
    var x=5;
    return {
        fun:function(){
            console.log(x);
        }
    };
};

var y=data();
y.fun();

闭包的作用域取决于函数的创建位置

// It has access to any x in this scope
var obj=function(){
    // It has access to any x in this scope
    this.fun=function(){
        // It has access to any x in this scope
        console.log(x);
    };
};

... 但是你在这里定义了 X:

var data=function(){
    // New scope here and none of the earlier code has access to it
    var x=5;
    return new obj();
};

… 并且只有函数表达式或声明在 inside 中的函数才能访问 x.

您可以将 x 作为参数传递给 obj

因为在您的第二个示例中,函数是在与变量相同的范围内创建的,因此可以访问它。在第一个示例中,定义函数时 x 不存在。