使对象保持静态,并且仍然指定和更改它

Make object static and still assign and change it

本文关键字:对象 静态      更新时间:2023-09-26

我想使用一个静态对象,将其分配给一个新变量并对其进行更改。

var MY_STATIC: {message: "I am static"};
var test = MY_STATIC;
test.message = "I am not static enough";
console.log(MY_STATIC.messsage);  ==> I am not static enough

但我希望MY_STATIC.消息仍然是"我是静态的",以便以后再次使用。如何在分配和更改时使对象保持不变

您可能需要使用Object.create()来创建MY_STATIC对象的新实例:

var MY_STATIC = {message: "I am static"};
var test = Object.create(MY_STATIC);
test.message = "I am not static enough";
console.log(test.message);
console.log(MY_STATIC.message);

在兼容ES5的引擎上,您可以"冻结"对象:

var static = Object.freeze({message: "I am static"});
snippet.log(static.message); // "I am static"
static.message = "Not!";
snippet.log(static.message); // "I am static"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

通过设置obj1=obj2,您通过引用传递它们。这里需要的是通过值传递它们,因此使用以下代码

 var MY_STATIC = {message:"Static I am"};
 function Clone(x) {
    for(prop in x)
    this[prop] = (typeof(x[prop]) == 'object')? 
                  new Clone(x[prop]) : x[prop];
 }
 (function(x){
     var test  = new Clone(x);
     test.message = 'Not static';
 })(MY_STATIC)