我正在用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可能不是为此而生的,但我想知道是否有办法实现这一点。
发布于 2012-07-26 20:13:40
仅调用Base.apply(...)不会设置继承。.apply所做的就是将this设置为第一个参数,其他什么都不设置。调用父构造函数很重要,但这还不够。
你要做的就是正确地设置原型链。也就是说,您必须将Derivation1.prototype设置为从Base.prototype继承的内容。
由于构造函数的每个实例都继承自构造函数的原型,因此您将看到如下代码
Derivation1.prototype = new Base();这是一个糟糕的想法,您已经可以看到原因:Base希望参数设置特定于实例的属性(在本例中为name)。但是我们并不关心这些属性,因为我们稍后会在带有Base.apply(this, ...)的子构造器中初始化它们。
因此,我们所需要的只是一个继承自Base.prototype的对象,幸运的是,ECMASCript 5定义了一个可以为我们完成此任务的函数(polyfill):
Derivation1.prototype = Object.create(Base.prototype);这将创建一个继承自Base.prototype的新对象。现在,由于用新对象替换了原始原型,因此必须设置constructor属性,使其正确指向Derivation1
Derivation1.prototype.constructor = Derivation1;下面是一个完整的例子。还可以看看this fiddle和this excellent answer by T.J. Crowder,它们解释了基本上相同的问题,但可能是以更好的方式。
示例
function BaseObject(name){
this.name = name;
}
// move properties shared by all instances to the prototype!
BaseObject.prototype.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']);
}
Derivation1.prototype = Object.create(BaseObject.prototype);
Derivation1.prototype.constructor = Derivation1;
// some useless method of the child "class"
Derivation1.prototype.someOtherMethod = function() {
return 42;
};
var first = new Derivation1();
first.sayWhoAmI();
https://stackoverflow.com/questions/11661078
复制相似问题