这个问题听起来有点混乱,所以我让代码解释一下:
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");
这对我不起作用。我该如何解决或更佳的问题-正确的解决方法是什么?
谢谢
答案 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");
FooPart
定义后致电printArg
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");