重置javascript构造函数时出了点问题

时间:2018-10-14 12:34:49

标签: javascript oop inheritance prototype

我正在尝试了解javascript中的继承。 我编写了一个基本示例,以实现父对象和子对象之间的简单继承。但是我认为重置构造函数时出了点问题。

function Mammal(){
}
function Dog(){

}
Mammal.prototype.walk = function(){
    console.log('walking..walking....');
}
Dog.prototype.bark = function(){
    console.log('wof wof!');
}

Dog.prototype = Object.create(Mammal.prototype);
Dog.prototype.constructor = Dog;
let dogInstance = new Dog();
dogInstance.walk();
dogInstance.bark();

3 个答案:

答案 0 :(得分:0)

这里的问题Dog.prototype = Object.create(Mammal.prototype);
尝试

[编辑]

function Mammal() {}
function Dog() {}
Mammal.prototype.walk = function () {
    console.log( 'walking..walking....' );
};
Dog.prototype.bark = function () {
    console.log( 'wof wof!' );
};

[/编辑]

let describe = Object.getOwnPropertyDescriptor;
let descriptor = Object.keys( Mammal.prototype ).reduce( function ( desc, key ) {
    desc[key] = describe( Mammal.prototype, key );
    return desc;
}, {} );
Dog.prototype = Object.create( Dog.prototype, descriptor );

[编辑]

Dog.prototype.constructor = Dog;
let dogInstance = new Dog();
dogInstance.walk();
dogInstance.bark();

或使用对象继承遵循

function Mammal( key ) { this.key = key; }
function Dog() {
    Mammal.call( this, "Dog" );
}
Dog.prototype = Object.create( Mammal.prototype );
Dog.prototype.bark = function () {
    console.log( 'wof wof!' );
};
Mammal.prototype.walk = function () {
    console.log( 'walking..walking....' );
    return `${this.key} from Mammal.`;
};
Dog.prototype.constructor = Dog;
let dogInstance = new Dog();
dogInstance.walk();
dogInstance.bark();

比较 dogInstance

 Mammal.prototype.isPrototypeOf( dogInstance );
 Dog.prototype.isPrototypeOf( dogInstance );

这对我有用:(

[/编辑]

答案 1 :(得分:0)

  

我认为重置构造函数时出了点问题。

不,there's not

您的问题是您这样做

Dog.prototype = Object.create(Mammal.prototype);

之后,在旧的bark对象上创建了Dog.prototype方法-您正在用新的空对象覆盖该方法。只需在做任何作业之前就完成:

function Mammal() {
}
Mammal.prototype.walk = function(){
    console.log('walking..walking....');
};

function Dog() {
}
Dog.prototype = Object.create(Mammal.prototype); // do this before creating properties
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
    console.log('wof wof!');
};

答案 2 :(得分:-1)

我对此不太确定,但这是问题所在:

Dog.prototype = Object.create(Mammal.prototype);

显然,您不能将哺乳动物原型直接提供给Dog原型

function Mammal() {
}
function Dog() {

}
Mammal.prototype.walk = function () {
	console.log( 'walking..walking....' );
}
Dog.prototype.bark = function () {
	console.log( 'wof wof!' );
}

Dog.prototype.mammal = Object.create( Mammal.prototype );
Dog.prototype.constructor = Dog;
let dogInstance = new Dog();
dogInstance.mammal.walk();
dogInstance.bark();

这似乎可行