Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

for in 对象优化 #43

Open
kangning1206 opened this issue Sep 29, 2017 · 0 comments
Open

for in 对象优化 #43

kangning1206 opened this issue Sep 29, 2017 · 0 comments

Comments

@kangning1206
Copy link
Owner

var man = {
   hands: 2,
   legs: 2,
   heads: 1
};

// 在代码的某个地方
// 一个方法添加给了所有对象
if (typeof Object.prototype.clone === "undefined") {
   Object.prototype.clone = function () {};
}

情况1

for (var i in man) {
   console.log(i, ":", man[i]);
}

错误的,会把继承方法和熟悉打印出来;

改进

for (var i in man) {
   if (man.hasOwnProperty(i)) { // 过滤
      console.log(i, ":", man[i]);
   }
}

使用对象上的 hasOwnProperty 方法判断;

推荐

var i, hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
    if (hasOwn.call(man, i)) { // 过滤
        console.log(i, ":", man[i]);
    }
}

使用了 Object上的hasOwnProperty 方法判断,避免 man方法上hasOwnProperty 被重写而导致的错误;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant