从外部设置应该在对象内可访问的变量
好吧,所以我知道通过闭包我可以做这样的事情:
var x,
obj = {
init: function() {
x = 123;
},
func: function() {
return x;
}
};
obj.init();
obj.func();
==> 123
但是,我希望能够从外部应用 x 的值(在对象之外,稍后)...我想也许我可以这样做:
var obj = {
init: function() {
// do something nice here...
},
func: function() {
return x;
}
};
var foo = {
doIt: function() {
var init = obj.init;
var x;
obj.init = function() {
x = 456;
init.apply(obj);
}
obj.init();
obj.func();
}
};
foo.doIt();
==> (error) x is not defined
但是,它不起作用..这可以以某种方式做到吗?
谢谢。
Ok, so I know through closure I can do something like this:
var x,
obj = {
init: function() {
x = 123;
},
func: function() {
return x;
}
};
obj.init();
obj.func();
==> 123
However, I would like to externally be able to apply values for x (outside of the object, and later on)... I thought that perhaps I could just do:
var obj = {
init: function() {
// do something nice here...
},
func: function() {
return x;
}
};
var foo = {
doIt: function() {
var init = obj.init;
var x;
obj.init = function() {
x = 456;
init.apply(obj);
}
obj.init();
obj.func();
}
};
foo.doIt();
==> (error) x is not defined
However, it doesn't work.. Is this possible to do somehow?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 new 运算符创建您类型的对象,并在该对象上设置属性。
You could create objects of your type using the
new
operator, and set the property on that object.