您要做的是在其他语言中称为类静态方法。
要在 Javascript 中做到这一点,您必须编写
Class.CONST = 1;
然后你可以用Class.CONST;
如果您尝试使用类似的实例方法访问它new Class().CONST
,它将是未定义的
回到您的问题, Class.prototype 中的所有内容只能由对象实例访问(即,通过 创建new
),而不是 Class 本身。为什么?
考虑实施new
Function.method('new', function () {
var that = Object.create(this.prototype);
var other = this.apply(that, arguments);
return (typeof other === 'object' && other) || that;
});
首先Object.create(this.prototype)
创建一个全新的对象,该对象继承自this.prototype
你声明的 via Class.prototype = { Const : 1 }
,然后它调用this.apply(that, arguments)
,它只是调用你声明的 Class 函数,并that
用作this
变量。然后它返回对象。您可以看到 Class 函数只是用作将事物填充到新生对象中的一种方式 create via new
。并且只有创建的对象才能访问原型方法。