/** * 创建一种类型,注意其属性 create 是一个方法,返回一个构造函数。 * 一般使用如下 * var X = Class.create(); 返回一个类型,类似于 java 的一个Class实例。 * 要使用 X 类型,需继续用 new X()来获取一个实例,如同 java 的 Class.newInstance()方法。 * * 返回的构造函数会执行名为 initialize 的方法, initialize 是 Ruby 对象的构造器方法名字。 * 此时initialize方法还没有定义,其后的代码中创建新类型时会建立相应的同名方法。 */ var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } }
Class.create实际上是返回一个函数,那么new的时候,做了些什么呢。参照MDN
When the code new foo(...) is executed, the following things happen:
A new object is created, inheriting from foo.prototype. The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.) new的时候会执行该返回的函数,即执行this.initialize.apply(this, arguments); 此时的this就是新生成的对象,这也就是说了所有对象的初始化工作全部委托给initialize函数了。