for...in...、Object.keys()、和Objec
2019-01-02 本文已影响0人
隔壁老王z
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
从上面的例子可以看出:其实这几个方法之间的差异主要在属性是否可可枚举,是来自原型,还是实例。
