gpt4 book ai didi

node.js - Mongoose 实例方法丢失执行上下文

转载 作者:太空宇宙 更新时间:2023-11-04 00:48:37 26 4
gpt4 key购买 nike

const mongoose = require("mongoose"),
requiredAttr = {type: String, required: true},
employeeSchema = new mongoose.Schema({
employeeNumber: {
type: String,
unique: true,
required: true
},
firstName: requiredAttr,
lastName: requiredAttr,
image: requiredAttr
},
{
timestamps: true //get createdAt, updatedAt fields
});

employeeSchema.methods.writeThis = () => {

console.log("doing writeThis");
console.log(this);
};

module.exports = mongoose.model("Employee", employeeSchema);

总有收获

doing writeThis
{} //would think I would see my employee properties here

然后我通过 Node 命令行测试一些基本的上下文切换,发现我无法执行以下操作(就像在浏览器中一样)

let test = { foo: "bar" };
let writeThis = () => { console.log(this); };
writeThis.apply(test); //or
writeThis.bind(test);

我错过了什么?

最佳答案

函数和箭头语法不能直接互换:

let writeThisArrow = () => {
console.log(this);
};
writeThisArrow.call({stuff: "things"});
// {}

function writeThisFunction() {
console.log(this);
}
writeThisFunction.call({stuff: "things"});
// {stuff: "things"}

在函数语法中,调用 this 会引用调用它的上下文。在 Arrow 语法中,调用 this 引用定义它的上下文。在您在 mongoose 中使用的情况下,它是文件本身的实际 this 。例如:

exports.stuff = "things";

let writeThisArrow = () => {
console.log(this);
};
writeThisArrow.call();
// {stuff: "things"}

箭头语法中的“this”是不可变的,您无法使用bind()call()apply()注入(inject)上下文。对于您的情况,只需切换回标准函数声明就可以了。

编辑:我使用了错误的措辞。 this 在箭头语法中不是不可变,您只是无法通过应用程序更改上下文。但是,您可以通过编辑定义它的上下文来更改它:

exports.stuff = "things";
let writeThisArrow = () => {
console.log(this);
};
writeThisArrow.call();
// {stuff: "things"}

exports.otherStuff = "other things";
writeThisArrow.call();
// {stuff: "things", otherStuff: "other things"}

关于node.js - Mongoose 实例方法丢失执行上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547772/

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