我更喜欢类似于下面的模式。您可以将其视为 4 步方法:
(function(parent) {
// 1. Declare private variables and functions that will be
// accessible by everybody within the scope of this
// function, but not outside of it.
var doSomethingAwesome = function() { .. }; // private function
var coolInteger = 42; // private variable
// 2. Create the constructor function
function ISGrader() {
..
}
// 3. Create shared public methods on the prototype object.
// These will be created only once, and shared between all objects
// which is more efficient that re-creating each method for each object.
ISGrader.prototype.printInfo = function() { .. };
ISGrader.prototype.putGrade = function(score) { .. };
// 4. Expose the constructor to the outside world.
parent.ISGrader = ISGrader;
})(window);
将所有内容都包含在自执行匿名函数中的原因是为了确保我们在内部创建的私有变量不会泄漏到封闭范围之外,并且基本上保持事物清洁。
像这样声明构造函数的另一个好处是,您可以window
通过更改一个单词轻松地将父对象从 say 更改为另一个命名空间对象。