Javascript:通过引用传递对象(Javascript: Passing objects by reference)

编程入门 行业动态 更新时间:2024-10-24 01:57:26
Javascript:通过引用传递对象(Javascript: Passing objects by reference)

在我的应用程序中,当我将它传递给不同的对象时,我不确定是否复制数据。 就像一个例子看看下面的代码一样:

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).

更多推荐

本文发布于:2023-07-26 19:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Javascript   Passing   reference   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!