自从你问了两年多了,但在谷歌搜索一个类似的方法,我最终在这里。除了(因为你实质上是在征求意见)之外,我没有看到你的实现有什么缺点,它似乎有点混淆你为什么将原型作为IIFE导入的原因。
否则,你已经得到了非常相似的“泄露原型模式”我已经基本上被视为这样的其他“标准”的实施:
(function (NS) {
'use strict';
// constructor for the Person "Class", attached to your global namespace
var Person = NS.Person = function (name) {
// set properties unique for each instance
this.name = name;
};
// may not be necessary, but safe
Person.prototype.constructor = Person;
// private method
var _privateMethod = function() {
// do private stuff
// use the "_" convention to mark as private
// this is scoped to the modules' IIFE wrapper, but not bound the returned "Person" object, i.e. it is private
};
// public method
Person.prototype.speak = function() {
console.log("Hello there, I'm " + this.name);
};
return Person;
})(window.NS = window.NS || {}); // import a global namespace
// use your namespaced Person "Class"
var david = new NS.Person("David");
david.speak();
也有类似的模块模式,其结构可能是更像是“类”的实施你是后:
(function (NS) {
'use strict';
// constructor for the Person "Class", attached to your global namespace
var Person = NS.Person = function (name) {
// reset constructor (the prototype is completely overwritten below)
this.constructor = Person;
// set properties unique for each instance
this.name = name;
};
// all methods on the prototype
Person.prototype = (function() {
// private method
var _privateMethod = function() {
// do private stuff
// use the "_" convention to mark as private
// this is scoped to the IIFE but not bound to the returned object, i.e. it is private
};
// public method
var speak = function() {
console.log("Hello there, I'm " + this.name);
};
// returned object with public methods
return {
speak: speak
};
}());
})(window.NS = window.NS || {}); // import a global namespace
// use your namespaced Person "Class"
var david = new NS.Person("David");
david.speak();
要点:https://gist.github.com/dgowrie/24fb3483051579b89512
我不明白这种方法如何有用...有什么优势?这似乎令人困惑。为什么不只是'A.prototype = {...}' – elclanrs 2012-08-16 11:07:25
将原型设置为和对象相同的操作不能用于扩展它。 – lietus 2012-08-16 11:45:32