我感兴趣的是在一个扩展的课程中使用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发布于 2022-01-21 03:30:17
显然,这与express不是类或构造函数,而是工厂函数这一事实有关。当您调用super()时,它调用express()并创建一个全新的对象,该对象不是您的对象,也没有您的原型。引用myApp._endpoints之所以有效,是因为构造函数将构造函数中的该属性分配给express()创建的对象,但该对象没有将原型附加到该对象,而是一个新创建的对象。
如果您从代码中删除extends express并注释掉super(),您将看到它都正常工作。
如果您在Javascript中将express更改为任何其他实际定义的class,则endpoints() getter工作得很好。
所以,您不能以这种方式扩展表达式。
express是可用的,您可以按照我们在使用class关键字之前的方式向它添加内容。
我不建议在这里使用class,因为它对任何阅读您的代码的人都暗示,他们可以为类定义方法,并期望它们能够工作(而它们不工作)。
相反,只需定义您自己的工厂函数,该函数调用express工厂函数,然后将属性添加到它返回的对象:
// factory function for my app
function Application() {
const app = express();
// add instance properties
app._endpoints = null;
// add getters/setters
Object.defineProperty(app, "endpoints", {
get: function () {
return this._endpoints;
},
set: function (paths: any[]) {
this._endpoints = new Set([...paths]);
},
enumerable: true,
configurable: true,
});
return app;
}这可以用作:
app = Application();或者:
app = new Application();发布于 2022-01-21 10:47:07
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://stackoverflow.com/questions/70795561
复制相似问题