hasOwnProperty vs propertyIsEnumerable [英] hasOwnProperty vs propertyIsEnumerable

查看:83
本文介绍了hasOwnProperty vs propertyIsEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以启发我,
hasOwnProperty和propertyIsEnumerable之间有什么区别:

Can anyone enlighten me, what is the difference between hasOwnProperty and propertyIsEnumerable:

function f(){
  this.a = 1;
  this.b = 2;
  this.c = function(){}
}
f.prototype = {
  d : 3,
  e : 4,
  g : function(){}
}

创建对象的实例:

var o = new f();

在这里我看不出差异。
在我看来他们做同样的事情

And here I can't see difference. In my opinion they are doing the same thing

o.hasOwnProperty('a'); //true
o.hasOwnProperty('b'); //true
o.hasOwnProperty('c'); //true
o.hasOwnProperty('d'); //false
o.hasOwnProperty('e'); //false
o.hasOwnProperty('g'); //false

o.propertyIsEnumerable('a'); //true
o.propertyIsEnumerable('b'); //true
o.propertyIsEnumerable('c'); //true
o.propertyIsEnumerable('d'); //false
o.propertyIsEnumerable('e'); //false
o.propertyIsEnumerable('g'); //false

如果我错了,请说明我

推荐答案

propertyIsEnumerable函数始终排除不会为hasOwnProperty返回 true 的属性。你没有做任何让属性不可枚举的东西,所以在你的测试中结果是一样的。

The "propertyIsEnumerable" function always excludes properties that would not return true for "hasOwnProperty". You've done nothing to make any properties not be enumerable, so in your test the results are the same.

你可以使用defineProperty来定义属性<强>不可枚举;在MDN 查看此参考资料

You can use "defineProperty" to define properties that are not enumerable; see this reference at MDN.

Object.defineProperty(obj, "hideMe", { value: null, enumerable: false });

这就像:

obj.hideMe = null;

除了该物业不会出现在中... / code>循环,使用 propertyIsEnumerable 的测试将返回 false

except the property won't show up in for ... in loops, and tests with propertyIsEnumerable will return false.

这整个主题是关于旧浏览器中没有的功能,如果这不是很明显的话。

This whole topic is about features not available in old browsers, if that's not obvious.

这篇关于hasOwnProperty vs propertyIsEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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