问题描述
我试图理解 JavaScript 中的对象"概念.在我看来,没有对象这样的东西,严格地说,只有对象化".以下是 W3C 关于 JavaScript 对象可变性的解释:
I am trying to understand the concept "object" in JavaScript. It seems to me that there is no such thing as object, but only "objectification," strictly speaking. Following is the W3C's explanation about the mutability of JavaScript object:
"对象是可变的...如果 y 是一个对象,下面的语句将不会复制 y...var x = y; 对象 x 不是 y 的副本.它是 y.两者都是 x并且 y 指向同一个对象.对 y 的任何更改也会更改 x,因为 x 和 y 是同一个对象."http://www.w3schools.com/js/js_object_definition.asp
"Objects are mutable...If y is an object, the following statement will not make a copy of y...var x = y; The object x is not a copy of y. It is y. Both x and y points to the same object. Any changes to y will also change x, because x and y are the same object." http://www.w3schools.com/js/js_object_definition.asp
令我困惑的是:x 和 y 是对象,还是指向同一个对象?的解释是否意味着 x 和 y 可以说是同一个对象,因为它们指向同一个对象?我想知道这是否是 JavaScript 对象的定义,我将不胜感激.谢谢你.
What is confusing to me is this: Are x and y objects, or do they point to the same object? Of does the explanation mean that x and y can be said to be the same object in that they point to the same object? I wonder if this is the definition of JavaScript object, and I will appreciate any help. Thank you.
推荐答案
在您的示例中,x
和 y
在技术上是对内存中同一对象的引用.
In your example, x
and y
are technically references to the same object in the memory.
当您创建一个对象,然后将该对象分配给不同的变量时,您所做的只是复制引用.
When you create an object, and then assign that object to a different variable, all you're doing is copying the reference.
这个例子应该能让你对发生的事情有所了解:
This example should give you a bit of an idea what's going on:
var a = {
prop: 123
};
var b = a;
a.foo = "bar";
alert("b.prop: " + b.prop);
alert("b.foo: " + b.foo);
delete a.prop;
alert("b.prop after `delete a.prop`: " + b.prop);
也就是说,为了简单起见,像这样的变量被称为对象".
向对象引用a
添加新属性"没有多大意义.
That said, variables like these are called "objects" for simplicity's sake.
It wouldn't make much sense to "Add a new property to the object reference a
".
这篇关于客体还是客体化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!