[英]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");
FooPart
after printArg
definition printArg
定义之后调用FooPart
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.