我有一个对象。
const ab = {
method: function() {
},
method1 : function () {
}
}
我想构建一个类,将上述对象中的所有函数作为静态方法。
所以如果我做类似的事情
Class Me extends ab;
应该等同于
Class Me {
static method() {}
static method1() {}
}
对此有何评论?
给定的对象 ab
对我来说是未知的(被接受为输入并且我需要返回类),我怎样才能实现同样的目标?
我不想使用传统的基于函数
的静态方法。
最佳答案
在 Javascript 中,您只需创建一个在其原型(prototype)链中具有给定对象的新对象。处理裸对象时最简单的方法是
const ab = {
method: function() {
return 1;
},
method1 : function () {
}
}
const ac = Object.create(ab);
console.log(ab.method());
console.log(ac.method());
新创建的 ac
对象就像您要求的具有静态方法的类。
设置显式原型(prototype)链的一个好处是您稍后在 ab
中修改的成员将反射(reflect)在 ac
中。
编辑:正如评论中所指出的,如果您想要一个类(其作用类似于构造函数),您需要一个具有从源对象复制的属性的函数:
const ab = {
method: function() {
return 1;
},
method1 : function () {
}
}
function Me() {}
// dummy member to show that Me is a class
Me.prototype.foo = function() { return 2; }
// assign static methods
Object.assign(Me, ab);
// Me is a class
var m = new Me();
console.log( m.foo() );
// but has static methods
console.log( Me.method() );
关于javascript - 如何从对象扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48808812/