向Object原型添加函数会导致函数显示在所有'for OB in OBJ'循环中 [英] Adding function to Object prototype causes function to show up in all 'for X in OBJ' loops

查看:126
本文介绍了向Object原型添加函数会导致函数显示在所有'for OB in OBJ'循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这里有一些示例javascript代码:

So, here's some sample javascript code:

Object.prototype.simpleFunction = function () {
    return true;
}
var tempObject = {};
for (var temp in tempObject) {
    console.log(temp);
}

请注意,如果执行此操作,您将获得'simpleFunction'输出Google Chrome中的 console.log 命令。 (我使用的是19.0.1084.46m。)

Note that if you execute this, you'll get 'simpleFunction' output from the console.log commands in Google Chrome. (I'm using 19.0.1084.46m .)

但是,各种相关的Object函数传递给的console.log

However, the wide variety of related Object functions are not passed to the console.log.

如何在对象原型中添加函数,而不会将它们显示在我的'中对于属性对象'循环?

How can I add functions onto the Object prototype without them showing up in my 'for property in object' loops?

编辑:我应该提到我最不想要的就是在那里抛出另一个'if'语句,因为它意味着我需要将它添加到所有中的循环。 :(

Edit: I should have mentioned that the last thing I wanted was to throw another 'if' statement in there, as it'd mean I'd need to add it to ALL for loops. :(

推荐答案

这就是为什么你应该经常检查 hasOwnProperty

Which is why you should always check hasOwnProperty:

for (var temp in tempObject) {
    if (Object.prototype.hasOwnProperty(tempObject, temp)) {
        console.log(temp);
    }
}

Crockford主张使用 Object.prototype.hasOwnProperty 而不是 tempObject.hasOwnProperty ,以防你覆盖你的对象中有hasOwnProperty

Crockford advocates using Object.prototype.hasOwnProperty instead of tempObject.hasOwnProperty, just in case you override hasOwnProperty in your object.

在ES5中,你可以将它设置为 enumerable

In ES5, you can set it to not be enumerable:

Object.defineProperty(Object.prototype, 'simpleFunction', {
    value: function() {
        return true;
    },
    enumerable: false, // this is actually the default
});

或者(在ES5中),您可以使用 Object.keys()只获取对象自己的密钥:

Alternatively (in ES5), you can use Object.keys() to only get the object's own keys:

Object.keys(tempObject).forEach(function(key) {
    console.log(key);
});

这篇关于向Object原型添加函数会导致函数显示在所有'for OB in OBJ'循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆