[英]What is the order of executing super() constructor and subclass methods in javascript object oriented programming?
Why is this
undefined in render()
method inside of the subclass?为什么在子类的render()
方法this
未定义? Why this
inside of the base class constructor refers to the created object based on subclass?为什么this
基础 class 构造函数内部引用了基于子类创建的 object ? I want to know the execution order in here.我想知道这里的执行顺序。
class baseClass { constructor() { this.render(); // why does "this" (not this.render()) refer to the created object based on derivedClass? } render() { console.log("won't get executed."); } } class derivedClass extends baseClass { foo = "foo" constructor() { super(); console.log(this); } render() { console.log(this.foo); // why is "this" undefined? alert("rendered"); } } new derivedClass;
To better understand how it works you can change your code a bit:为了更好地理解它是如何工作的,你可以稍微改变你的代码:
class baseClass {
bar = 'bar';
constructor() {
console.log(
`In baseClass constructor this is ${JSON.stringify(this, null, 2)}`
);
this.render(); // why does "this" (not this.render()) refer to the created object based on derivedClass?
}
render() {
console.group();
console.log(this);
console.log('baseClass rendered');
console.groupEnd();
}
}
class derivedClass extends baseClass {
foo = 'foo';
constructor() {
super();
console.log(
`In derivedClass constructor this is ${JSON.stringify(this, null, 2)}`
);
this.render();
}
render() {
console.group();
console.log(this);
console.log('derivedClass rendered');
console.groupEnd();
}
}
new derivedClass();
It will output:它将 output:
In baseClass constructor this is {
"bar": "bar"
}
derivedClass { bar: 'bar' }
derivedClass rendered
In derivedClass constructor this is {
"bar": "bar",
"foo": "foo"
}
derivedClass { bar: 'bar', foo: 'foo' }
derivedClass rendered
So the sequence is as follows:所以顺序如下:
derivedClass
constructor is called when you do new derivedClass();
执行new derivedClass();
时调用derivedClass
构造函数;baseClass
constructor它调用baseClass
构造函数baseClass
"owns"数据成员填充了baseClass
“拥有”的内容derivedClass
, that's why you see "derivedClass rendered" when render is called from the baseClass
constructor.虽然这些方法属于derivedClass
,这就是为什么在从baseClass
构造函数调用 render 时看到“derivedClass 渲染”的原因。derivedClass
are added添加了derivedClass
的数据成员derivedClass
constructor calls render
again. derivedClass
构造函数再次调用render
。 It is somewhat counter-intuitive, especially if you come from OOP background with C++, Java, etc. And I think this is the reason why some try to avoid classes and this
in JavaScript entirely. It is somewhat counter-intuitive, especially if you come from OOP background with C++, Java, etc. And I think this is the reason why some try to avoid classes and this
in JavaScript entirely.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.