如何在构造函数中创建JS对象并"parent object"为构造函数参数?



这个问题听起来可能有点令人困惑,所以我让代码解释:

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");

这对我不起作用。我怎样才能解决这个问题或更好 - 正确的方法是什么?

谢谢

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. 您应该在定义printArg后调用FooPart
  2. 您应该使用this.parent来访问parent

问题是你在尝试调用它之后定义了printArg

定义没有此问题的"类"的传统方法是:

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");

定义"实际"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");

最新更新