我目前正在将一个相当大的 actionscript 库转换为在我的 nodejs 项目中工作。在这样做的时候,我偶然发现了一些可能是个问题的东西:从类中构建类。
有没有办法使用一个对象作为另一个对象的基础(IE:从基础对象继承所有成员,然后从扩展对象覆盖同名成员)?
现在这就是我正在做的事情,虽然现在管理起来有点困难,因为有 3 个以上的类构建在另一个之上:
// The base object which others may extend
function A() {
this.a = "pie";
}
A.prototype.yum = function() {
return this.a + " is AWESOME!";
}
// The "extends A" object.
// Instead of creating an instance of "B", I current just create an instance of "A",
// then adding the members from "B" to it at which point I return the "A" instance.
function B() {
var a = new A();
a.b = "pie";
// Notice how I have to declare the overwriting function here instead of being able
// to drop it into B's prototype. The reason this bothers me is instead of just
// having one copy of the function(s) stored, each time a "new B" is created the
// function is duplicated... for 100s of "B" objects created, that seems like poor
// memory management
a.yum = function () {
return "I like " + this.a + " and " + this.b;
};
return a;
}
console.log((B()).yum());
是否可以按照以下方式做一些事情?
我知道这是无效的,但它给出了这个想法。
function A(){
this.a = "pie"
}
A.prototype.yum = function () {
return this.a + " is AWESOME!";
}
function B(){
// Throws an "illegal left hand assignment" Exception due to overwriting `this`;
this = new A();
this.b = "cake"
}
B.prototype.yum = function () {
return "I like "+this.a+" and "+this.b;
}
console.log((new B()).yum());
注意:
1:我知道 javascript 没有类;它使用对象和原型。不然我也不会问。
2:这不是要转换的实际代码(尝试);这是一个普遍的例子
3:请不要推荐图书馆。我知道有时它们很有价值,但我宁愿不必为项目维护、依赖和包含整个库。
回答: 我知道改变原生成员原型是不好的形式,但我认为这是值得的,因为它缺乏可能的功能,而且它的大小。
Object.prototype.extendsUpon = function (p) {
var h = Object.prototype.hasOwnProperty;
for(var k in p)if(h.call(p,k))this[k]=p[k];
function c(c){this.constructor=c;}
c.prototype = p.prototype;
this.prototype = new c(this);
this.__base__ = p.prototype;
}
function object_Constructor_built_ontop_of_another_constructor() {
this.extendsUpon(base_Object_to_built_atop_off);
this.__base__.constructor.apply(this, arguments);
// From here proceed as usual
/* To access members from the base object that have been over written,
* use "this.__base__.MEMBER.apply(this, arguments)" */
}