javascript - 构造函数的问题

问题描述

我在 JavaScript 中有一个很奇怪的效果

function Enemy(name,x,y) {
    this.name = name;
    this.x = x;
    this.y = y;
    console.log("create normal");
    //console.log("tworzenie normalnego " + this.name);
}

function EnemyShoot(name,y) {
    Enemy.call(this,name,y); // call base constructor
    this.type = "shooter";
    console.log("create shooter");
}

EnemyShoot.prototype = Object.create(Enemy.prototype);
EnemyShoot.prototype.constructor = EnemyShoot;

const enemyN = new Enemy("Normal",5,0);
const enemyS = new EnemyShoot("Shooter",10,20);

。看看我的朋友:

问题是 - 为什么当我注释 console.log("create normal"); 并取消注释下一条指令时一切正常,而现在不行。我认为现在不行,因为我在控制台中: 创建正常 创造射手 反而: 创建正常 创建正常 创建射手

提到更改后,一切正常。

解决方法

执行此操作时:

const enemyN = new Enemy("Normal",5,0);

您导致 Enemy 构造函数触发,因此在控制台中您得到:

create normal

然后,当你执行这个:

const enemyS = new EnemyShoot("Shooter",10,20);

您导致 EnemyShoot 构造函数被触发,其中包含对 Enemy 的调用,因此您会在控制台中获得第二个 create normal

然后,您将获得要执行的 EnemyShoot 控制台指令,因此您将在控制台中获得 create shooter 作为第三行。

注释第一个 console.log 并在它简单地替换前两个输出后取消注释以显示相对于上下文对象的数据,这(由于 Enemy.call(this,name,x,y) 行,确保第二行将 this 上下文替换为继承实例的上下文。这正是它应该如何操作的。

function Enemy(name,y) {
    this.name = name;
    this.x = x;
    this.y = y;
    console.log("create normal");
    //console.log("tworzenie normalnego " + this.name);
}

function EnemyShoot(name,y) {
    Enemy.call(this,y); // call base constructor
    this.type = "shooter";
    console.log("create shooter");
}

EnemyShoot.prototype = Object.create(Enemy.prototype);
EnemyShoot.prototype.constructor = EnemyShoot;

const enemyN = new Enemy("Normal",0);
const enemyS = new EnemyShoot("Shooter",20);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...