我想写一个JS库,并像这样处理它:
var c1 = Module.Class(); c1.init(); var c1 = Module.Class(); c2.init();当然,c1和c2不能共享相同的变量。 我想我知道如何用物体做到这一点,那将是:
var Module = { Class = { init = function(){ ... } } }但问题是我不能有多个类的实例,如果我这样写。 所以我试图在功能上做到这一点,但我认为我没有做对。
(function() { var Module; window.Module = Module = {}; function Class( i ) { //How can "this" refer to Class instead of Module? this.initial = i; } Class.prototype.execute = function() { ... } //Public Module.Class = Class; })();我甚至没有线索,但我接受其他方式创建此模块的建议。 我不知道它是否也相关,但我在这个库中使用了jQuery。
I want to write a JS library and handle it like this:
var c1 = Module.Class(); c1.init(); var c1 = Module.Class(); c2.init();And of course, c1 and c2 can not share the same variables. I think I know how to do this with objects, it would be:
var Module = { Class = { init = function(){ ... } } }But the problem is I can't have multiple instances of Class if I write in this way. So I'm trying to achieve the same with function, but I don't think I'm doing it right.
(function() { var Module; window.Module = Module = {}; function Class( i ) { //How can "this" refer to Class instead of Module? this.initial = i; } Class.prototype.execute = function() { ... } //Public Module.Class = Class; })();I don't have a clue if it's even possible, but I accept suggestions of other way to create this module. I don't know if it's relevant also, but I'm using jQuery inside this library.
最满意答案
用法:
var c1 = Module.Class("c"); var c2 = Module.Class("a"); var n = c1.initial(); // equals 'c' c1.initial("s"); n = c1.initial(); // equals 's'模块代码:
(function(window) { var Module = window.Module = {}; var Class = Module.Class = function(initial) { return new Module.Class.fn.init(initial); }; Class.fn = Class.prototype = { init: function(initial) { this._initial = initial; }, initial: function(v){ if (v !== undefined) { this._initial = v; return this; } return this._initial; } }; Class.fn.init.prototype = Class.fn; })(window || this);这是使用JavaScript“模块”设计模式; 这与JavaScript库(如jQuery)使用的设计模式相同。
下面是关于“模块”模式的一个很好的教程: JavaScript模式模式:深入
Usage:
var c1 = Module.Class("c"); var c2 = Module.Class("a"); var n = c1.initial(); // equals 'c' c1.initial("s"); n = c1.initial(); // equals 's'Module Code:
(function(window) { var Module = window.Module = {}; var Class = Module.Class = function(initial) { return new Module.Class.fn.init(initial); }; Class.fn = Class.prototype = { init: function(initial) { this._initial = initial; }, initial: function(v){ if (v !== undefined) { this._initial = v; return this; } return this._initial; } }; Class.fn.init.prototype = Class.fn; })(window || this);This is using the JavaScript "Module" Design Pattern; which is the same design pattern used by JavaScript libraries such as jQuery.
Here's a nice tutorial on the "Module" pattern: JavaScript Module Pattern: In-Depth
更多推荐
发布评论