这个问题听起来可能有点令人困惑,所以我让代码解释:
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");
- 您应该在定义
printArg
后调用FooPart
- 您应该使用
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");