参数:' xxx'不是一个功能

时间:2017-01-17 17:07:47

标签: javascript ecmascript-6

我有以下原型:

Object.prototype.find = function (path, obj = null) {
    let previous = null;
    obj = !obj ? this : obj;
    for (let i = 0, p = path.split(/[\[\]\.]/), len = p.length; i < len; i++) {
        if (p[i] == '') { continue; }
        let item = p[i];
        obj = obj[item];
        previous = obj;
    }
    return obj;
}

然后我这样称呼它:

let data = [
    {
        id: 1    
    },
    {
        id: 2
    }
];

console.log(data.find('[0].id')) // Error refers to this line
// The result should return 1

然后我收到以下错误:

  

未捕获的TypeError:xxx不是函数

为什么它会给我这个错误?

1 个答案:

答案 0 :(得分:7)

您在数组上调用find。这意味着你正在点击the native array find method(因为它比你在find原型上定义的Object方法更接近原型链。

数组find方法期望第一个参数是一个函数。

如果您想调用find方法,则需要明确地执行此操作:

Object.prototype.find("xxx", data); // or
Object.prototype.find.call(data, "xxx");

...或者给它一个名字,不要被Array.prototype上的现有方法屏蔽。

(这是为什么扩展原生对象的原型是一个坏主意的一个很好的例子)