使对象静态并仍然分配和更改它
Make object static and still assign and change it
我想使用一个静态对象,将它赋值给一个新的变量并改变它。
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.message 仍然 "I am 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 的引擎上,您可以 "freeze" an object:
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
,您将通过 ref 传递它们。您在这里需要的是按值传递它们,因此请使用此代码
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)
我想使用一个静态对象,将它赋值给一个新的变量并改变它。
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.message 仍然 "I am 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 的引擎上,您可以 "freeze" an object:
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
,您将通过 ref 传递它们。您在这里需要的是按值传递它们,因此请使用此代码
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)