[英]My Javascript classes are inheriting attributes from their prototype, but not functions! Why is this?
[英]Inheriting attributes from prototype
我正在做学校作业,我想继承以前的构造函数的属性。 我使用了object.create,但是当我创建一个继承先前属性的新对象时,它没有正确分配属性。
我试图更改编写新对象的语法,并尝试查看学校的笔记。
function GameObject(createdAt,name,dimensions){
this.createdAt = createdAt;
this.name = name;
this.dimensions = dimensions;
}
GameObject.prototype.destroy = function(){
return `${this.name} was removed from the game.`
}
const hi = new GameObject(
"microsoft","hi","300 X 600")
console.log(hi)
console.log(hi.destroy())
/*
=== CharacterStats ===
* healthPoints
* takeDamage() // prototype method -> returns the string '<object name> took damage.'
* should inherit destroy() from GameObject's prototype
*/
function CharacterStats(healthPoints){
this.healthPoints = healthPoints
GameObject.call(this, healthPoints)
}
CharacterStats.prototype.takeDamage = function(){
return this.name + " took damage."
}
CharacterStats.prototype = Object.create(GameObject.prototype)
const yay = new CharacterStats(
"microsoft","hi","300 X 600")
console.log(yay)
我希望yay对象不仅可以正确继承healthPoints属性,而且还可以继承GameObject的属性
这些属性不是由与原型相关的任何内容创建的,而是由您对GameObject
构造函数的调用创建的。 但是您没有在此处传递正确的论点,应该
function CharacterStats(createdAt, name, dimensions, healthPoints) {
// ^^^^^^^^^ ^^^^ ^^^^^^^^^^
GameObject.call(this, createdAt, name, dimensions);
// ^^^^^^^^^ ^^^^ ^^^^^^^^^^
this.healthPoints = healthPoints;
}
那你可以做
const yay = new CharacterStats("stackoverflow", "marcus", "300 X 600", 8);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.