0
const bg = {
    sX: 0,
    sY: 0,
    w: 275,
    h: 226,
    x: 0,
    y: cvs.height - 226,

    draw: function(){
        ctx.drawImage(sprite, this.sX, this.sY, this.w, this.h, this.x, this.y, this.w, this.h);
        ctx.drawImage(sprite, this.sX, this.sY, this.w, this.h, this.x + this.w, this.y, this.w, this.h);
    }
}

bg.x = 20;

If const cannot be updated or redeclared, how is it possible for methods within constant objects to be updated?

lucidcloud
  • 73
  • 6
  • 4
    bg is a _reference_ to the object. The reference can't be changed, but the object being referenced can still be mutated. – user120242 May 03 '20 at 05:38
  • 1
    Does this answer your question? [Why can I change value of a constant in javascript](https://stackoverflow.com/questions/23436437/why-can-i-change-value-of-a-constant-in-javascript) – ggorlen May 03 '20 at 05:40
  • On a related note, `Object.freeze` can be used to prevent changes to the object. `Object.seal` may also be of interest – user120242 May 03 '20 at 05:44

1 Answers1

2
bg.x = 20;

bg stores the reference

You are changing a property here and not the reference

So this would be invalid

let rg ={}
bg = rg

const bg = {
    sX: 0,
    sY: 0,
    w: 275,
    h: 226,
    x: 0
}

bg.x = 20;

let rg = {}
bg = rg
kooskoos
  • 4,622
  • 1
  • 12
  • 29