【发布时间】:2011-08-26 22:07:36
【问题描述】:
我的原型示例是以下伪代码:
var kind = ...;
...
var type = new kind();
...
var person = new type();
...
var john = new person();
但这里的问题是type 不是一个函数,所以new type() 不起作用。
是否可以向对象添加特定属性以使其为new 所接受?
对我来说最重要的是原型链,这对我来说很重要,即 person.[[Prototype]] 应该是 type 等,以防 new 无法实现。
创建子类型链不是一种选择。这里type 是person 的元类型,而不是它的超类型。同样kind 是一个元元类型。以下测试可以阐明要求:
完成后,我想要这些阳性测试:
console.log(john instanceof person); // should be true
console.log(person instanceof type); // should be true
console.log(type instanceof kind); // should be true
和这些负面测试:
console.log(john instanceof type); // should be false
console.log(john instanceof kind); // should be false
console.log(person instanceof kind); // should be false
我听说通过分配给__proto__ 属性可以做一些这种魔术,但不知道如何。显然,如果有便携式解决方案(例如使用 Object.create),则更可取。
【问题讨论】:
-
那么您是否只是想创建一个
person,即-atype,即-akind?所以每次你创建一个新的person,你就在隐式地创建一个新的kind,并自动获得该类型的所有功能? -
不,我不想要子类型链,我希望
person成为type的实例,就像john是person的实例一样。 -
这令人困惑,尤其是您对 FunkyFresh 的回答的评论。 1)您想要类型之间的is-a关系吗? 2)您不想从基类型继承任何结构或功能?
-
我更新了问题以澄清这个问题。这现在有意义吗?
标签: javascript metaprogramming prototype-programming