I'm currently trying to access the method of a specific ancestor in my dependency chain. Specifically, I want to run ParentClass.logName()
from my initialized GrandChildClass. This is how I access the ParentClass prototype (approach taken from Get parent class name from child with ES6? ).
class AncestorClass { constructor (name, id){ this.name = name + id; } logName () { console.log(this.name); } } class ParentClass extends AncestorClass { constructor (name, id) { super(name, 1); this.name = name + id; } } class ChildClass extends ParentClass { constructor (name, id) { super(name, 2); this.name = name + id; } } class GrandchildClass extends ChildClass { constructor (name, id){ super(name, 3); this.name = name + id; } } const grandchild = new GrandchildClass('testName', 4); const parent = Object.getPrototypeOf((Object.getPrototypeOf(grandchild.constructor))); console.log(parent); const initParent = new parent(); initParent.logName();
So I got the prototype and initialized it with the new
keyword but for some reason initParent.logName()
returns NaN.
So how do I call to ParentClass.logName from my grandchild without initializing ParentClass directly?
You initialize parent with an empty constructor, which means both attribute are undefined
and undefined + undefined
gives NaN
.
const initParent = new parent('foo', 1);
initParent.logName() // print 'foo1'
class AncestorClass { constructor (name, id){ this.name = name + id; } logName () { console.log(this.name); } } class ParentClass extends AncestorClass { constructor (name, id) { super(name, 1); this.name = name + id; } } class ChildClass extends ParentClass { constructor (name, id) { super(name, 2); this.name = name + id; } } class GrandchildClass extends ChildClass { constructor (name, id){ super(name, 3); this.name = name + id; } } const grandchild = new GrandchildClass('testName', 4); const parent = Object.getPrototypeOf((Object.getPrototypeOf(grandchild.constructor))); console.log(parent); const initParent = new parent('foo', 1); initParent.logName();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.