我正在嘗試將我的 javascript 類從舊樣式轉換為新樣式。問題是,使用新樣式的 JavaScript 要求super在訪問之前呼叫建構式this。我必須擴展一個我不是所有者的類,并且在該建構式中它呼叫一個方法,我在使用我自己的屬性的地方覆寫該方法。如何解決?
class A {
constructor() {
this.create()
}
create() {}
reload() {
this.create()
}
}
class B extends A {
constructor(options) {
super()
this.options = options
}
create() {
let title = this.options.title // TypeError: Cannot read properties of undefined (reading 'title')
}
}
uj5u.com熱心網友回復:
我會讓原型create成為空操作,然后在super()完成后呼叫一個函式。
class A {
constructor() {
this.create()
}
create() {}
}
class B extends A {
constructor(options) {
super()
this.options = options
this.createB();
}
createB() {
const title = this.options.title;
console.log(title);
}
create() {}
}
new B({ title: 'foo' });
我想你也可以.create在超級運行之后分配,將它從無操作轉換回你想要的功能。
class A {
constructor() {
this.create()
}
create() {}
}
function createB() {
}
class B extends A {
constructor(options) {
super()
this.options = options
this.create = () => {
const title = this.options.title;
console.log(title);
};
this.create();
}
create() {}
}
new B({ title: 'foo' });
uj5u.com熱心網友回復:
我會在 B's 添加一個守衛create,并讓它的建構式再次執行它:
class A {
constructor() {
this.create();
}
create() {
console.log("I don't want to run this");
}
reload() {
this.create();
}
}
class B extends A {
constructor(options) {
super();
this.options = options;
this.create(); // ... but now
}
create() {
if (!this.hasOwnProperty("options")) return; // not now...
let title = this.options.title;
console.log("title", title);
}
}
let b = new B({ title: "my title" });
console.log("let's reload");
b.reload();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/428130.html
標籤:javascript 班级 子类
