我的问题,见下文,是如何声明 pre-ES6 类的 STATIC 函数和常量以便它们可以被继承?
在问题之前给出了当前 ES6 类和 ES6 之前的类的回顾,因此我们都使用相同的约定。
在后 ES6 中,我们可以在类中定义一个静态函数,如下所示:
class MyClass {
static someMethod () {
console.log('Doing someMethod');
}
}
在 ES6 之前,我可以创建一个基类,如下所示:
var MyClassBase = function(str){
this.m_Data = str; // This acts a bit like a constructor where you can assign data within the class
};
你可以创建一个 ES6 之前的实例
var myclassbase = new MyClassBase("Wibble");
您可以创建该类的 pre-ES6 非静态成员函数:
MyClassBase.prototype.EchoData = function(){
console.log(this.m_Data);
}
您需要一个实例来调用该非静态成员函数:
var myclassbase = new MyClassBase("Wibble");
myclassbase.EchoData();
为了继承,在 ES6 之前我会做类似的事情:
var MyClass = function(str){
MyClassBase.call(this, str);
};
MyClass.prototype = new MyClassBase(); // inherit
[编辑]:但是@adiga 在评论中建议(查看他们有用的链接)更好的方法是:
var MyClass = function(str){
MyClassBase.call(this, str);
};
MyClass.prototype = Object.create(MyClassBase.prototype);
MyClass.prototype.constructor = MyClass;
这就是所有的背景。现在是关于静力学的问题。
问题:ES6 之前如何在基类 MyClassBase
中创建静态函数,它可以在没有实例的情况下调用,例如:
MyClassBase.StaticFunctionInMyClassBase();
MyClass.StaticFunctionInMyClassBase(); // This could be the inherited function from MyClassBase,
// or may be a redefined overridden function in MyClass
问题:如何将静态常量分配给 MyClass
和 MyClassBase
pre-ES6,无需实例即可访问?例如,
var result = MyClassBase.TWO_PLUS_TWO; // Echos 4, a predefined static value in MyClassBase
var result = MyClass.TWO_PLUS_TWO; // Echos 5, if TWO_PLUS_TWO has been redefined in MyClass,
// or 4 if TWO_PLUS_TWO has no been redefined in MyClass
Kai 的建议静态可以包含在以下内容中:
var MyClassBase = function(str){
this.m_Data = str;
};
MyClassBase.STATIC_STRING = "Ooops";
但是,当我创建继承 MyClassBase
的类 MyClass
时,MyClass.STATIC_STRING
是 undefined
。我只能使用 MyClassBase.STATIC_STRING
访问“Ooops”。这是正常的类惯例吗?
最佳答案
How do I create static functions which can be called without an instance, and how do I assign static constants which can be accessed without an instance?
方法和常量都只是类(构造函数)对象的属性,都是通过赋值创建的:
var MyClassBase = function(str){
this.m_Data = str;
};
MyClassBase.STATIC_STRING = "Ooops";
另见 JavaScript: Class.method vs. Class.prototype.method或 Static variables in JavaScript .
When I create my class
MyClass
which inheritsMyClassBase
, thenMyClass.STATIC_STRING
is undefined. Is that normal class conventions?
是的,这在ES5继承中很正常。 To emulate ES6, you would need to manually set the prototype of the constructor :
Object.setPrototypeOf(MyClass, MyClassBase);
(或者在 ES5 中,确实使用了现已弃用的 __proto__
)。
但是请注意,足够多了 you want to explicitly refer to MyBaseClass
anyway .
关于javascript - 类中的 Pre ES6 静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67648500/