gpt4 book ai didi

node.js - 不支持选项 [methodName]

转载 作者:太空宇宙 更新时间:2023-11-03 22:10:10 24 4
gpt4 key购买 nike

我正在尝试扩展 js 应用程序中的 Object 类。

方法如下:

Object.prototype.safeGet = function(props, defaultValue) {
console.log(this, props, defaultValue);
if (typeof props === 'string') {
props = props.split('.');
}
if (this === undefined || this === null) {
return defaultValue;
}
if (props.length === 0) {
return this;
}
return this.safeGet(props.slice(1), defaultValue);
};

当我加载这个时,我得到:

the options [safeGet] is not supported

然后该方法似乎被调用(虽然我在代码中没有调用),并带有以下参数(来自 console.log):

SchemaString {
enumValues: [],
regExp: null,
path: 'source',
instance: 'String',
validators:
[ { validator: [Function],
message: 'Path `{PATH}` is required.',
type: 'required' } ],
setters: [],
getters: [],
options:
{ type: [Function: String],
index: true,
required: true,
safeGet: [Function],
runSettersOnQuery: undefined },
_index: true,
isRequired: true,
requiredValidator: [Function],
originalRequiredValue: true } [Function] undefined

使用 NodeJS

$ node --version
v4.8.3

知道发生了什么吗?更改名称没有帮助。

最佳答案

问题是您要向 Object.prototype 添加一个可枚举属性,该属性在对象迭代期间将“可见”,Mongoose 似乎正在这样做(并且将其与函数混淆)它需要调用)。

相反,您想使用Object.defineProperty添加不可枚举的属性:

Object.defineProperty(Object.prototype, 'safeGet', {
value : function(props, defaultValue) {
console.log(this, props, defaultValue);
if (typeof props === 'string') {
props = props.split('.');
}
if (this === undefined || this === null) {
return defaultValue;
}
if (props.length === 0) {
return this;
}
return this.safeGet(props.slice(1), defaultValue);
}
});

但是,如果您主要使用此方法来处理 Mongoose 对象/文档,您可能应该考虑创建 plugin相反。

关于node.js - 不支持选项 [methodName],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44699880/

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