【发布时间】:2018-10-16 07:44:01
【问题描述】:
我有这个类对象,它需要在构造函数内部有它的绘制函数来更新分数,如果它在分数之外返回未定义。
export class Hud {
constructor(world) {
var self = this;
this.canvas = world.canvas;
this.ctx = world.ctx
this.score = 0;
this.draw = function() {
this.ctx.font = "16px Arial";
this.ctx.fillStyle = "#0095DD";
this.ctx.fillText("Score: " + self.score, 8, 20);
}
}
}
我的其他类对象在构造函数之外具有绘图功能,就像这样可以正常工作,
export class Ball {
constructor(world) {
var self = this;
this.canvas = world.canvas;
this.ctx = world.ctx;
self.x = canvas.width / 2;
self.y = canvas.height - 30;
this.ballRadius = 10
this.dx = 2;
this.dy = -2
}
draw() {
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.ballRadius, 0, Math.PI * 2);
this.ctx.fillStyle = "#0095DD";
this.ctx.fill();
this.ctx.closePath();
}
}
我的问题是两者之间的区别是什么。我认为如果它在构造函数中定义,则变量可以在整个类对象中访问。我想我很困惑,构造函数之外应该有函数吗?将所有内容都放在构造函数中似乎很轻松。
【问题讨论】:
-
泛型方法放在类体中,而自己的需要闭包的方法放在构造函数中。它可以节省内存和 CPU 开销来定义通用(原型)方法,而不是为每个对象实例实例化单独的函数实例。在类中说明方法也可以更清晰,更易于阅读。
-
当在原型上声明类方法时(例如在构造函数之外),只有该函数的一个实例存在并被所有类实例重用,例如
Ball.prototype.draw === ball1.draw === ball2.draw。当在实例上声明方法时(例如在构造函数内部),会为每个实例创建一个新函数,例如ball1.draw !== ball2.draw.
标签: javascript