简体   繁体   English

如何在构造函数中创建一个JS对象,并将“父对象”作为构造函数参数?

[英]How to create a JS object within constructor and “parent object” as constructors argument?

The question might sound a bit confusing so I'll let the code explain: 这个问题听起来有点混乱,所以我让代码解释一下:

 function Foo(arg) { const argument = arg; const fooPart = new FooPart(this); this.printArg = function() { console.log(argument); } } function FooPart(foo) { this.parent = foo; this.parent.printArg(); } let foo = new Foo("this is the argument"); 

This is not working for me. 这对我不起作用。 How can I solve this problem or better - what would be the correct approach for this? 我该如何解决或更佳的问题-正确的解决方法是什么?

Thanks 谢谢

 function Foo(arg) { this.argument = arg; this.fooPart = new FooPart(this); } Foo.prototype.printArg = function() { console.log(this.argument); } function FooPart(foo) { this.parent = foo; this.parent.printArg(); } let foo = new Foo("this is the argument"); 

  1. You should call FooPart after printArg definition 您应该在printArg定义之后调用FooPart
  2. You should use this.parent to access parent 您应该使用this.parent访问parent

The problem is that you define printArg after trying to call it. 问题是您尝试调用定义了printArg

The traditional way to define a "class" which doesn't have this problem would be: 定义不存在此问题的“类”的传统方法是:

 function Foo(arg) { this.argument = arg; this.fooPart = new FooPart(this); } Foo.prototype.printArg = function() { console.log(this.argument); } function FooPart(foo) { this.parent = foo; this.parent.printArg(); } let foo = new Foo("this is the argument"); 

The more modern version to define an "actual" class is: 定义“实际” class的更现代的版本是:

 class Foo { constructor(arg) { this.argument = arg; this.fooPart = new FooPart(this); } printArg() { console.log(this.argument); } } class FooPart { constructor(foo) { this.parent = foo; this.parent.printArg(); } } let foo = new Foo("this is the argument"); 

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

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