自從你問了兩年多了,但在谷歌搜索一個類似的方法,我最終在這裏。除了(因爲你實質上是在徵求意見)之外,我沒有看到你的實現有什麼缺點,它似乎有點混淆你爲什麼將原型作爲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