首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JS在构造函数内部和外部定义的方法有什么区别

JS在构造函数内部和外部定义的方法有什么区别
EN

Stack Overflow用户
提问于 2018-10-16 07:31:42
回答 1查看 1.3K关注 0票数 3

我有一个类对象,它需要在构造函数内使用它的绘图函数来更新分数,如果它在分数之外,则返回未定义的分数。

代码语言:javascript
复制
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);
      }
   }
}

我的其他类对象在构造函数之外有绘图函数,所以工作得很好,

代码语言:javascript
复制
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();
}
}

我的问题是,这两者之间的区别是什么。我认为如果它是在构造函数中定义的,那么变量在整个类对象中都是可访问的。我想我搞糊涂了,在构造函数之外应该有函数吗?把所有的东西都放在构造器中似乎是很容易的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-16 07:38:40

类(而不是构造器)中定义的函数依赖于每个实例所链接的类原型。在构造函数中定义的函数将成为每个实例自己的属性。如果在构造函数中定义了函数,则每个实例都将获得其自己的函数副本。如果不这样做,实例将遵循原型链,并且所有实例将指向相同的函数。例如:

代码语言:javascript
复制
class Hud {
    constructor(world) {
        this.name = world
        this.draw = function() {
            console.log("draw on instance from", this.name)
          }
       }
    draw_outside(){
        console.log("draw on class from", this.name )
    }
}

let h1 = new Hud('h1')
let h2 = new Hud('h2')

console.log(h1.__proto__.draw)         // draw not on prototype
console.log(h1.__proto__.draw_outside) // draw_outside is

console.log(h1.draw === h2.draw)                  // each object gets its own draw
console.log(h1.draw_outside === h2.draw_outside)  // but both point to the same draw_outside

console.log(Object.getOwnPropertyNames(h1))       // only draw & name

// both access `this` the same way when called on an instance:

h1.draw()
h1.draw_outside()

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52826037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档