向Object原型添加函数会导致函数显示在所有'for OB in OBJ'循环中

Sor*_*umb 8 javascript

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

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

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

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

如何在Object原型中添加函数而不将它们显示在我的" for property in对象"循环中?

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

Jos*_*ber 12

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

for (var temp in tempObject) {
    if (Object.prototype.hasOwnProperty(tempObject, temp)) {
        console.log(temp);
    }
}
Run Code Online (Sandbox Code Playgroud)

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


在ES5中,您可以将其设置为不enumerable:

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

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

Object.keys(tempObject).forEach(function(key) {
    console.log(key);
});
Run Code Online (Sandbox Code Playgroud)