美文网首页
for...in...、Object.keys()、和Objec

for...in...、Object.keys()、和Objec

作者: 隔壁老王z | 来源:发表于2019-01-02 16:58 被阅读0次
function A(a,aa) {
  this.a = a;
  this.aa = aa;
  this.getA = function() {
    return this.a;
  }
}
// 原型方法
A.prototype.aaa = function () {};

var B = new A('b', 'bb');
B.myMethodA = function() {};
// 不可枚举方法
Object.defineProperty(B, 'myMethodB', {
  enumerable: false,
  value: function() {}
});

// 1. Object.keys
Object.keys(B)  //["a", "aa", "getA", "myMethodA"]

// 2. Object.getOwnPropertyNames
Object.getOwnPropertyNames(B);  //["a", "aa", "getA", "myMethodA", "myMethodB"]

// 3. for...in...
for(i in B){ console.log(i) }  
// a 
// aa
// getA
// myMethodA
// aaa

从上面的例子可以看出:其实这几个方法之间的差异主要在属性是否可可枚举,是来自原型,还是实例。


对比.png

相关文章

网友评论

      本文标题:for...in...、Object.keys()、和Objec

      本文链接:https://www.haomeiwen.com/subject/lyozlqtx.html