在我的应用程序中,当我将它传递给不同的对象时,我不确定是否复制数据。 就像一个例子看看下面的代码一样:
var DataStore = function(data) { this.data = data; // <-- typeof data === 'object' } var Controller = function() { var dataStore = new DataStore({foo: 'bar'}); var plugin = new Plugin(dataStore.data); } var Plugin = function(data) { this.data = data; } var app = new Controller();当我创建Plugin时,它将从dataStore传递数据属性。 然后将其分配给Plugin内的属性。 请记住,传递的数据是我的问题的对象,这是在内存中创建两个变量还是插件中的data属性引用DataStore对象中的属性?
如果在赋值之后它没有保留引用,那么我怎样才能将DataStore传递到插件并在本地保存引用呢? 或者我需要将DataStore作为全局变量保存在我的应用程序范围中,并从插件全局引用它?
In my applications I am not sure if I am duplicating data when I pass it around to different objects. Just as an example have a look at the following code:
var DataStore = function(data) { this.data = data; // <-- typeof data === 'object' } var Controller = function() { var dataStore = new DataStore({foo: 'bar'}); var plugin = new Plugin(dataStore.data); } var Plugin = function(data) { this.data = data; } var app = new Controller();When I create Plugin it is passed the data property from dataStore. It is then assigned to a property inside Plugin. Keeping in mind that the data being passed around is an object my question is, is this creating two variables in memory or does the data property in Plugin reference the property in the DataStore object?
If it doesn't keep the reference after assignment, how can I pass the DataStore into Plugins and keep a reference to it locally? Or would I need to keep DataStore as a global variable in my application scope and reference it globally from the plugins?
最满意答案
dataStore.data和plugin.data引用同一个对象 - 在这两个“类”中的任何一个中dataStore.data plugin.data对象(因为没有更好的术语)会导致对象被两个对象突变(因为它们都持有对同一个对象)。
Both dataStore.data and plugin.data reference the same object - mutating the object in either of these "classes" (for lack of a better term) will result in the object being mutated for both of them (since they are both holding references to the same object).
更多推荐
发布评论