gpt4 book ai didi

javascript - 创建钩子(Hook)后

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:17 25 4
gpt4 key购买 nike

假设我有一个 Mongoose 模型m

这个模型 m 是用一个 Schema s 创建的,它添加了一个方法来记录事情:

s.methods.log = function(s) {
this.theLogger(s);
}

必须随时提供 theLogger,因此我在 postinit Hook 处提供 theLogger。

这个有效:

const x = await m.findOne({_id: ...});
x.log("something");

这里的问题是这行不通:

const x = new m();
x.log("something"); // <--- theLogger is not defined.

有什么方法可以在使用 new 运算符创建 x 时 Hook 吗?

最佳答案

我仍然不知道这些钩子(Hook)是否存在,所以我最终通过使用函数扩展模型解决了这个问题:

return ((parent) => {
function HookedModel(a, b) {
// Pre new hooks here <-----
this.constructor = parent;
parent.call(this, a, b);
// Post new hooks here <-----
}
// Copy all static functions:
for (const k in parent) {
if (parent.hasOwnProperty(k)) {
HookedModel[k] = parent[k];
}
}
HookedModel.__proto__ = parent.__proto__;
HookedModel.prototype = Object.create(parent.prototype);
HookedModel.prototype.constructor = HookedModel;
return HookedModel;
})(model);

关于javascript - 创建钩子(Hook)后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com