我正在努力组织我的代码。我的项目中有几个模块,我想对其进行组织。
关键是我想到的一切都行不通。我目前正在考虑四个想法:
简单对象 - 由于范围问题没有用。使用
this.a
可以,但是this
根据调用者的不同而具有不同的含义,因此它不可靠。例如,我曾经将一个函数分配给WebSocket
类,但在调用该函数时突然this
引用了WebSocket
实例通过WebSocket
事件。我可以在每次调用该函数时使用bind(foo)
,但我猜一定还有另一种方法。var foo = { a: 3, s: function() { alert(a); // a doesn't exist in this scope alert(this.a); // 'this' isn't always foo alert(foo.a); // I would have to put 'foo.' before each variable // reference, but I'm sure that's not the way to do it } };
实例 -
a
未定义。再次强调,这个
并不可靠。var foo = function() { this.a = 3; this.s = function() { alert(a); }; }; var foo_instance = new foo(); foo_instance.a = 4; foo_instance.s(); // Error: a is not defined
实例关闭 - 不返回任何内容;它保持
未定义
。var foo = (function() { this.a = 3; this.s = function() { alert(a); }; })(); // foo === undefined
使用 getter/setter 闭包 - 在 Chrome 上运行良好,但 IE 不支持 getter/setter。
var foo = (function() { var a = 3; return { get a() { return a; }, set a(v) { a = v; }, s: function() { alert(a); // Doesn't work in IE as getters/setters are // not supported } }; })();
如何有效地组织我的模块,以便我可以安全地以跨浏览器的方式访问属性?
谢谢。
最佳答案
3 未定义,因为您没有返回任何内容。不要将属性和方法分配给“this”,而是尝试这样做:
var foo = (function() {
var self = {};
self.someProperty = someValue;
self.someFunction = function () {
}
return self;
}());
foo 现在将返回一个具有定义的属性和方法的对象。通过这种方式,您永远不必想知道“this”实际上指的是什么。
关于javascript - 如何在 'modules' 中组织我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290989/