2017-06-22 44 views
0

我试图在我的js应用程序中扩展Object类。不支持[methodName]选项

这里的方法:

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 

任何想法是怎么回事?更改名称将无济于事。

回答

0

问题是,您正在将一个enumerable属性添加到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); 
    } 
}); 

但是,如果您使用此方法主要是为了对付猫鼬对象/文件,你应该考虑创建一个改为plugin