首页 > 解决方案 > 角度类属性到常量变量

问题描述

我已经为常量变量分配了一个类属性。常量是可变的,当我改变常量时,类属性也在改变。

    export class SampleClass implements OnInit {
        name = "a";

        onclick() {
            const tempName = this.name;
            tempName = "b"; // error
            console.log(this.name); // a
        }
    }

[编辑]和我上面问的一样的场景,

    export class AppComponent implements OnInit {
      name = [
        {"option":"Never",            "weight":0},
        {"option":"Sometimes",        "weight":1},
        {"option":"Many time",        "weight":2},
        {"option":"Most of the time", "weight":3},
        {"option":"All the time",     "weight":4}
      ];

      ngOnInit() {
        const tempName = this.name;
        tempName[0].weight = 10; // constant is changing

        console.log(this.name); // this.name[0].weight also set to 10
        console.log(tempName); 
      }
    }

如何取消链接?

在这里检查

标签: angular

解决方案


@mbojko 在他的评论中是正确的:

除了上面提到的重新分配const之外,原语(包括字符串)是按值复制的,而不是按引用复制的,并且tempName = "b"; 不会改变 this.name 的值

首先,它根本不会编译,即使出于某种原因编译,它也不会改变this.name.

在此处输入图像描述


推荐阅读