我试图从子构造函数方法中调用父构造函数中的方法,但我无法这样做。是否可以在子类的构造函数中调用父方法?
我们需要这个构造,因为我们需要在不同的作用域:this: inside es6 class?中访问 inside es6 class?。我创建了一个小示例代码,它展示了我们的问题:
class Foo{
constructor() {
this.classMethod = () => {
console.log('In Foo');
};
}
}
class Bar extends Foo{
constructor() {
super()
this.classMethod = () => {
console.log('In Bar');
super.classMethod(); // How to call the this.classMethod() in Foo?
};
}
}
bar = new Bar();
bar.classMethod();预期结果应是:
In Bar
In Foo实际产出:
In Bar
TypeError: super.classMethod is not a function当classMethod被移出构造函数的范围时,一切都按预期的方式工作,除了我们无法像上面链接的StackOverflow问题中所述的那样访问StackOverflow。
class Foo{
constructor() { }
classMethod() {
console.log('In Foo');
};
}
class Bar extends Foo{
constructor() {
super();
}
classMethod () {
console.log('In Bar');
super.classMethod();
};
}
bar = new Bar();
bar.classMethod();实际产出:
In Bar
In Foo可以通过子类构造函数中的方法调用父类构造函数中的方法吗?
发布于 2019-01-23 10:48:30
试试这个:
class Foo{
constructor() {
this.classMethod = () => {
console.log('In Foo');
};
}
}
class Bar extends Foo{
constructor() {
super();
const originalClassMethod = this.classMethod.bind(this);
this.classMethod = () => {
console.log('In Bar');
originalClassMethod();
};
}
}
bar = new Bar();
bar.classMethod();在你的第一段和第二段之间有一个重要的区别。请注意,如果您定义了这样一个类:
class Foo {
someMethod() {
return 'foo';
}
}然后,如果在控制台中键入:Foo.prototype.someMethod,则可以访问该方法。但是,该方法不能绑定到任何实例,因为您还没有使用new关键字,对吗?
但是,如果您定义了这样的类:
class Foo {
constructor() {
this.someMethod = () => 'foo';
}
}这种情况将不再是这样,因为在第二个示例中,类被实例化时属性someMethod是在类的实例上定义的。
发布于 2019-01-23 11:09:10
尝尝这个
class Foo {
constructor() {
this.classMethod = function () {
console.log('In Foo');
};
}
}
class Bar extends Foo{
constructor() {
super();
this.barClassMethod = function () {
console.log('In Bar');
this.classMethod(); // How to call the this.classMethod() in Foo?
};
}
}
bar = new Bar();
bar.barClassMethod();发布于 2019-01-23 11:13:36
另一个诀窍是实例化构造函数中的父类并从那里调用该方法:
class Foo {
constructor() {
this.classMethod = () => {
console.log('In Foo');
};
}
}
class Bar extends Foo {
constructor() {
super()
this.classMethod = () => {
console.log('In Bar');
(new Foo).classMethod()
};
}
}
bar = new Bar();
bar.classMethod()https://stackoverflow.com/questions/54325383
复制相似问题