在擴展課程中與 Express 一起作業是我的興趣所在。我想為屬性定義 getter 和 setter,但這樣做不會將方法系結到實體。一種解決方法是創建一個自定義的getter和setter方法并將其系結到建構式上,但是感覺不對。
const express = require("express");
export default class Application extends express {
_endpoints;
constructor() {
super();
this._endpoints = null;
}
get endpoints() {
return this._endpoints;
}
set endpoints(paths: []) {
this._endpoints = new Set(...paths);
}
}
const myApp = new Application();
console.log(myApp) // ...express-app-object, _endpoints, and nothing related to the getter and setter defined.
console.log(myApp._endpoints) // null
console.log(myApp.endpoints) // undefined
uj5u.com熱心網友回復:
express它顯然與不是類或建構式的事實有關,它是一個工廠函式。當您呼叫時super(),它會呼叫express()并創建一個全新的物件,該物件不是您的物件,也沒有您的原型。參考myApp._endpoints有效,因為您的建構式將建構式中的該屬性分配給express()創建的物件,但該物件沒有附加您的原型,它是 Express 創建的一個新物件。
如果您extends express從代碼中洗掉 并注釋掉super(),您將看到一切正常。
如果您將 express 更改為classJavascript 中定義的任何其他實際值,您的endpoints()getter 就可以正常作業。
因此,您不能以這種方式擴展 express。
express 原型是可用的,您可以按照我們在使用class關鍵字之前的方式向其中添加內容。
uj5u.com熱心網友回復:
export class Application extends express {
private _endpoints = null;
constructor() {
super();
Object.defineProperty(this, "endpoints", {
get: function () {
return this._endpoints;
},
set: function (paths: any[]) {
this._endpoints = new Set([...paths]);
},
enumerable: true,
configurable: true,
});
}
}
使用是正常的:
const app = new Application();
console.log(app.endpoints) // null
app.endpoints = ['/auth/signin', '/auth/signout']
console.log(app.endpoints) // Set(2) { '/auth/signin', '/auth/signout' }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417870.html
標籤:
