我正在用 JavaScript 设计一些类层次结构。到目前为止它工作正常,但我看不出如何确定一个对象是否是父类的“实例”。例子:
function BaseObject(name){
this.name = name;
this.sayWhoAmI = function(){
console.log(this.name + ' is a Derivation1 : ' + (this instanceof Derivation1));
console.log(this.name + ' is a Derivation2 : ' + (this instanceof Derivation2));
console.log(this.name + ' is a BaseObject : ' + (this instanceof BaseObject));
};
}
function Derivation1(){
BaseObject.apply(this, ['first derivation']);
}
function Derivation2(){
BaseObject.apply(this, ['second derivation']);
}
var first = new Derivation1();
var second = new Derivation2();
first.sayWhoAmI();
记录这个:
first derivation is a Derivation1 : true
first derivation is a Derivation2 : false
first derivation is a BaseObject : false
同时second.sayWhoAmI();
记录:
second derivation is a Derivation1 : false
second derivation is a Derivation2 : true
second derivation is a BaseObject : false
我觉得first
和second
object 都应该说它们是BaseObject
.
我知道 JavaScript 可能不是为此而设计的,但我想知道是否有办法实现这一点。