简体   繁体   English

Javascript-defineProperty与原型

[英]Javascript - defineProperty vs Prototype

I have just run into an unexpected problem whilst trying to create an array prototype for a function that emulates what is available in .net (linq) called SingleOrDefault(). 我在尝试为模拟.net(linq)中称为SingleOrDefault()的函数的函数创建数组原型时遇到了一个意外问题。

Whilst the prototype function worked fine, I found that when iterating over a normal array using the following syntax for (var x in y) ... my function name appeared as one of the properties and broke my logic. 虽然原型函数运行良好,但我发现,使用以下语法对(var x in y)的以下语法进行迭代时,我的函数名称显示为属性之一,破坏了我的逻辑。

As a result of some googling I have redefined the function (below). 由于进行了一些谷歌搜索,我重新定义了该函数(如下)。

My question is, is the code in the Current block the right way to extend the Array object without causing any unwanted side effects? 我的问题是, Current块中的代码是扩展Array对象而不引起任何不良副作用的正确方法吗?

Previous 以前

Array.prototype.singleOrDefault = function (predicate) {
    var items = applyPredicate(this, predicate);
    if (items.length > 1) {
        throw new Error(errorOutput.multipleElements);
    }
    return (items) ? items[0] : null;
};

Current 当前

Object.defineProperty(Array.prototype, 'singleOrDefault', {
    value: function (predicate) {
        var items = applyPredicate(this, predicate);
        if (items.length > 1) {
            throw new Error(errorOutput.multipleElements);
        }
        return (items) ? items[0] : null;
    },
    enumerable: false
});

Yes your 'current' code is correct, not as supported with older browsers as the previous code which is a downside if you need ie6/7 support (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty ). 是的,您的“当前”代码是正确的,较旧的浏览器不像以前的代码那样受支持,如果您需要ie6 / 7支持,那么这是一个缺点(请参阅https://developer.mozilla.org/en-US/docs/Web/ JavaScript / Reference / Global_Objects / Object / defineProperty )。

You could use the object.hasOwnProperty method with the 'previous' code to achieve the same effect when you are iterating: 您可以将object.hasOwnProperty方法与“先前”代码一起使用,以在迭代时实现相同的效果:

for (var x in y) {
     if (y.hasOwnProperty(y[x])) {
        //would filter out SingleOrDefault in your examples above
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM