Javascript 当使用';创建对象时,为什么不作为对象属性访问闭包;新';然后马上回来?
现在我调用Javascript 当使用';创建对象时,为什么不作为对象属性访问闭包;新';然后马上回来?,javascript,closures,javascript-objects,Javascript,Closures,Javascript Objects,现在我调用data()函数,它将创建一个局部变量x,并返回与obj函数和new关键字一起创建的对象,该关键字具有属性fun,其值是另一个函数。那么为什么返回的fun方法不访问closurex var obj=function(){ this.fun=function(){ console.log(x); }; }; var data=function(){ var x=5; return new obj(); }; var y=data();
data()
函数,它将创建一个局部变量x
,并返回与obj
函数和new
关键字一起创建的对象,该关键字具有属性fun
,其值是另一个函数。那么为什么返回的fun
方法不访问closurex
var obj=function(){
this.fun=function(){
console.log(x);
};
};
var data=function(){
var x=5;
return new obj();
};
var y=data();
y.fun();
现在,我们不再创建新对象,而是放置相同的对象并返回它。
现在它可以访问closurex
。为什么
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();
};
…并且只有函数表达式或声明位于匿名函数表达式中的函数才能访问x
您可以将
x
作为参数传递给obj
。闭包的范围基于创建函数的位置
// 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();
};
…并且只有函数表达式或声明位于匿名函数表达式中的函数才能访问x
您可以将
x
作为参数传递给obj
。因为在第二个示例中,函数是在与变量相同的范围内创建的,因此可以访问它。在第一个示例中,定义函数时不存在x 因为在第二个示例中,函数是在与变量相同的范围内创建的,因此可以访问它。在第一个示例中,定义函数时不存在x x
不在this.fun的字面范围内。您只需将其作为参数传递给newobj
var obj=function(x).
把你的问题翻过来,为什么你认为x
应该在this.fun
的第一个代码块中可用?x
不在this.fun
的字面范围内。您只需将其作为参数传递给newobj
var obj=function(x).
把你的问题抛到它的头上,为什么你认为x
应该在this.fun
的第一个代码块中可用?