我想知道在下面的代码中处理复制一个对象到另一个对象上发生了什么。在某些情况下,他们的行为就像是改变另一个的相同对象。我发现很多关于JavaScript对象如何通过引用被复制的帖子,所以它们实际上是相同的对象。例如,从http://www.w3schools.com/js/js_object_definition.asp:一个案例中的对象相同,另一个案例中的对象不同?
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
var x = person; // This will not create a copy of person.
x.age = 10; // This will change both x.age and person.age
The object x is not a copy of person. It is person. Both x and person
is the same object. Any changes to x will also change person, because
x and person are the same object.
不过,我也发现那里的对象似乎是单独的对象的情况。在一种情况下,它如何表现为相同的对象,但在另一种情况下,却有不同的对象?我将不胜感激情况任何光:
例子:http://codepen.io/gratiafide/pen/yagQGr?editors=1010#0
HTML:
<div id="app">
<my-component>
</my-component>
</div>
JS:
var MyComponent = Vue.extend({
template: '<div v-on:click="test()" class="red">1. Click here to copy the name object to message and change the value of name to see if the value of message gets changed also. (It does not).</div> message: {{ message | json}} <br> name: {{ name | json}}<div v-on:click="test2()" class="red">2. Now click here to see if updating the name object also changes the message object. It does! Why here and not in #1?</div><div v-on:click="test3()" class="red">3. Click here to see yet another way of updating the name object also changes the message object. Why here and not in #1?</div>',
data: function() {
return {
message: {},
name: {}
}
},
ready: function(){
this.message = {};
},
methods: {
test: function(){
this.message = {'t1':"m1"};
this.name = this.message;
this.name = {'t2':"m2"};
},
test2: function(){
this.message = {'t1':"m1"};
this.name = this.message;
for (var key in this.name) {
this.name[key] = '';
}
},
test3: function(){
this.message = {'t1':"m1"};
this.name = this.message;
Vue.set(this.name, 't1', 'm2');
}
}
});
Vue.component('my-component', MyComponent);
new Vue({
el: '#app'
});
CSS:
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
.red{
color:red;
}
body {
font-family: 'Open Sans', sans-serif;
background: rgba(0,0,0,.5);
margin: 0;
}
#app {
width: 500px;
margin: 0 auto;
padding: 10px 20px;
background: rgba(255,255,255,.9);
}
在JavaScript中,*赋值*(或方法参数)不*创建所述对象的副本/克隆/副本。此规则也适用于*其他对象内的属性*。 – user2864740
[JavaScript是传递引用还是传值语言?]的可能的重复(http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass按值语言) – vlaz
如果你做'a = {}; b = a;'和操作'b',你改变_same_对象。如果你做'a = {}; b = a; b = {}'now'b'指向一个_different_对象,所以操纵一个不会改变另一个。这几乎是一切,真的。 – vlaz