草庐IT

Javascript 继承 : Parent's array variable retains value

coder 2024-07-18 原文

我在这里尝试在 JavaScript 中使用继承,我发现 Parent 类中的数组值被 Child 类继承时出现问题。下面的代码是正常的继承:

var Parent = function() {
    this.list = [];
};

var Child = function() {};

Child.prototype = new Parent;
Child.prototype.constructor = Child;

var obj1 = new Child;

obj1.list.push("hello");

console.log(obj1.list); // prints ["hello"];

当我将新的 Child 对象(继承包含名为 list 的数组变量的 Parent)初始化为 obj1 并尝试推送 obj1 .list 的值为“hello”,obj1.list 打印 ["hello"] .. 目前一切顺利。

当我执行上面的示例并尝试将新的 Child 对象初始化为 obj2 然后推送 obj2 时,问题就来了>list 的值为“goodbye”,obj2.list 现在打印 ["hello", "goodbye"]。 (见下面的代码:)

var obj2 = new Child;

obj2.list.push("goodbye");

console.log(obj2.list); // prints ["hello", "goodbye"];

我可能在这里有一个误解,但是 Parent 中的 list 数组以某种方式保留了值,我不知道为什么。

这是一个很大的麻烦,因为如果我将 Parent 类重用到许多其他子类,如上面的情况,如果 Parent 具有与其子类共享的数组变量,该值也将共享给其他子类,这对我来说是出乎意料的。

我期望的是,Child 类代表新对象,当 Child 类初始化为 时,Parent 类也是如此obj1,然后当我将新的 Child 对象初始化为 obj2 时,从 obj1 推送的值不应与 共享>obj2.

-- 问题--

有谁能帮我找出为什么上面例子中的list(Parent的数组变量)保留/共享Child发起的值对象(在上面的例子中,obj1obj2)?

如果您有其他解决方案可以解决此问题,那将非常感谢,但我很乐意先找出上述问题。

最佳答案

当子对象具有从其原型(prototype)对象继承的属性时,真正发生的是子对象具有对原型(prototype)的引用,其中包含该属性。 child 没有自己的副本。因此,两个 child 都在使用相同的数组——您分配给 Child.prototype 的(一个)Parent 原型(prototype)对象上的那个数组。

首先是一些图片,然后是更多文字。 :-)

new Parent() 给你这个:

+-----------------+
| Parent instance |
+-----------------+
| list = []       |
+-----------------+

...which you then assign to Child.prototype.

Then, new Child() gives you this:

+------------------+
| Child instance 1 |
+------------------+        +-----------------+
| (prototype)      |------->| Parent instance |
+------------------+        +-----------------+
                            | list = []       |
                            +-----------------+

Doing new Child() again gives you another one:

+------------------+      +------------------+
| Child instance 1 |      | Child instance 2 |
+------------------+      +------------------+
| (prototype)      |---+  | (prototype)      |---+
+------------------+   |  +------------------+   |
                       |                         |
                       |                         |     +-----------------+
                       +-------------------------+---->| Parent instance |
                                                       +-----------------+
                                                       | list = []       |
                                                       +-----------------+

So as you can see, all of the Child instances are sharing the same Parent instance (their prototype), which has an array on it.

When you say:

var obj = new Child();
obj.list.push("foo");

...这是 JavaScript 引擎在看到 obj.list 时所做的事情:

  1. 查看obj 是否有其自己的 属性list。如果没有,那么:
  2. 查看obj 的原型(prototype)是否有其自己的 属性list。如果没有,那么:
  3. 查看 obj 的原型(prototype)的原型(prototype)是否有其自己的属性list
  4. 等等直到我们用完原型(prototype)。

在你的例子中,由于 obj 没有它的 own list 属性,引擎会查看它的原型(prototype)(您分配给 Child.prototype 的 Parent 实例),在本例中它确实具有该属性。所以就用了那个。它不会复制给 child 或其他任何东西,而是使用。当然,因为它是一个数组,所以将某些东西推到数组上实际上就是将它推到数组上。

如果您要分配一些东西给obj.list,那么obj 将得到它的自己的 list 属性,打破链条。因此,将 this.list = []; 放入 Child 将为每个 child 提供自己的列表。

只要原型(prototype)上有对象引用,您就会看到这一点,其中对象是可以修改的类型(“可变”对象)。数组、日期、普通对象 ({})、正则表达式等,它们都有状态并且都可以修改,所以您会看到它们。 (String 实例是不可变的,因此虽然发生了同样的事情,但您看不到任何影响,因为字符串无法更改。)

对于图元,虽然您继承了它们,但您无法更改它们的状态(您只能用具有不同状态的新图元替换它们),因此您看不到相同的效果.所以如果 obj 从它的原型(prototype)继承属性 foo,并且 foo42alert(obj .foo) 将从原型(prototype)中获取值并显示“42”。改变 foo 的唯一方法是说 obj.foo = 67 或类似的——这给 obj 自己的 foo 的副本,不同于原型(prototype)的副本。 (即使您使用 ++-- 之类的东西也是如此,例如 ++obj.foo;它确实被评估为 obj.foo = obj.foo + 1).

关于Javascript 继承 : Parent's array variable retains value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9311032/

有关Javascript 继承 : Parent's array variable retains value的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  4. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  5. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  6. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  7. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  8. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  9. ruby-on-rails - Rails 中的 NoMethodError::MailersController#preview undefined method `activation_token=' for nil:NilClass - 2

    似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai

  10. ruby-on-rails - Rails - 使用/自定义 URL : '/dashboard' 指定根路径 - 2

    如何使此根路径转到:“/dashboard”而不仅仅是http://example.com?root:to=>'dashboard#index',:constraints=>lambda{|req|!req.session[:user_id].blank?} 最佳答案 您可以通过以下方式实现:root:to=>redirect('/dashboard')match'/dashboard',:to=>"dashboard#index",:constraints=>lambda{|req|!req.session[:user_id].b

随机推荐