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

时间:2019-08-14 13:56:29

标签: javascript oop 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");

这对我不起作用。我该如何解决或更佳的问题-正确的解决方法是什么?

谢谢

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

问题是您在尝试调用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");