简体   繁体   English

JavaScript从子类设置父值

[英]JavaScript Set Parent Value from Child Class

I am in JavaScript. 我在用JavaScript。

Below I have a Main object that instantiates the Handle class within it. 在下面,我有一个Main对象,在其中实例化Handle类。 I prefer composition over inheritance which is why I've avoided prototyping -- unless there is a way around it.. 我更喜欢使用组合而不是继承,这就是为什么我避免原型设计的原因 -除非有解决方法。

function Main() {

  this.changeMe = 1;

  this.init = function() {
    handle = new Handle();
    handle.setMe();

  }
};

function Handle() {
  this.setMe = function() {
     // parent::changeMe = 2; <-- How would I change the parent value?    
  }
};

var app = new Main();
main.init();
console.log(main.changeMe); <-- How do I get that to 2?

I am trying to figure out how I change the parent value. 我试图弄清楚如何更改父值。 Do you know how? 你知不知道怎么?

The init code is wrong here, syntax error.. You are creating new object of Main() in app variable yet trying to access it from 'main' variable which is not initialized. 初始化代码在这里是错误的,语法错误。.您正在app变量中创建Main()的新对象,但尝试从未初始化的“ main”变量访问它。

try 尝试

var app = new Main();
app.init();
console.log(app.changeMe);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM