简体   繁体   English

如果常量不能在 javascript 中更新或重新声明,为什么这段代码可以工作?

[英]If constants cannot be updated or redeclared in javascript, why does this piece of code work?

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?如果 const 不能更新或重新声明,常量对象中的方法怎么可能更新?

bg.x = 20;

bg stores the reference bg 存储参考

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM