Javascript:成员变量访问闭包
我想知道如何处理 JavaScript 中闭包中的成员变量。以下代码警报“6”。
function testy()
{
function blah()
{
this.a = 5;
this.func = function()
{
this.a = 6;
alert(this.a);
}
}
var x = new blah;
x.func();
}
但此代码会发出警报 5.
function testy()
{
function execute(func)
{
func();
}
function blah()
{
this.a = 5;
this.func = function()
{
execute(function()
{
this.a = 6;
});
alert(this.a);
}
}
var x = new blah;
x.func();
}
如何传递仍访问封闭对象的成员变量的闭包?
I'm wondering how to deal with member variables in closures in JavaScript. The following code alerts "6".
function testy()
{
function blah()
{
this.a = 5;
this.func = function()
{
this.a = 6;
alert(this.a);
}
}
var x = new blah;
x.func();
}
but this code alerts 5.
function testy()
{
function execute(func)
{
func();
}
function blah()
{
this.a = 5;
this.func = function()
{
execute(function()
{
this.a = 6;
});
alert(this.a);
}
}
var x = new blah;
x.func();
}
How do I pass a closure which still accesses the member variables of the enclosing object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将函数调用为
func();
并且默认情况下不指定上下文this
将解析为浏览器中的全局上下文,即window
.. 您可以在此处使用三个选项。使
this
本地现在
that
指向正确的this
。将
this
作用域绑定到函数这会将正确/预期的
this
作用域绑定到您的函数。请注意Function.prototype.bind
是 ES5,会破坏旧版浏览器。_.bind
是一个合理的跨浏览器替代方案。编辑执行
将上下文作为额外参数传递以执行。然后execute会调用
Function.prototype.call
< /a> 确保使用所需的上下文调用该函数Your calling the function as
func();
and by default without specifying a contextthis
will resolve to the global context which iswindow
in the browser.. There are three options you can use here.make
this
localNow
that
points to the correctthis
.bind
this
scope to the functionThis will bind the correct / expected
this
scope to your function. Note thatFunction.prototype.bind
is ES5 and will break older browsers._.bind
is a reasonable cross browser alternative.edit execute
Your passing the context as an extra parameter to execute. Then execute will call
Function.prototype.call
to make sure that the function is called with the desired context试试这个:
Try this: