var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
Object.hasOwnProperty.call(foo, 'bar')//true
Object.hasOwnProperty.call(foo, 'hasOwnProperty')//true
Object.hasOwnProperty.call(foo, 'toString')//false
- getOwnProperyNames
- 返回可枚举和不可枚举的属性
- 返回对象上的属性为自身的属性
- 不会获取原型链上的值
function Parent(){
this.son = 'son'
}
Parent.prototype.show = function(){
console.log('Parent')
}
var Child = Object.create(Parent.prototype, {
tooBar: {
value: function (){console.log('tooBar')},
enumerable: false//变为不可枚举属性
}
})
Child.show = function() {
console.log('show')
}
console.log(Object.getOwnPropertyNames(Child))//tooBar, show
function enumerable(obj) {
if(typeof obj !== 'object') return
var arr = []
if(Object.keys) {
arr = Object.keys(obj)
} else {
for(var key in obj) {
if(Object.prototype.hasOwnProperty.call(obj, key )){
arr.push(key )
}
}
}
return arr
}
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function() {};
// 继承
var ChildClass = Object.create(ParentClass.prototype, {
// 不可枚举属性
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
// 自身可枚举属性
ChildClass.foo = 1;
console.log(Object.keys(ChildClass))// foo
function Person() {}
Person.prototype.show1 = function() {}
Person.prototype.show2 = function() {}
Person.prototype.show3 = function() {}
var p1 = new Person()
p1.show4 = 'show4'
for(var key in p1){
console.log(key)
}
返回 show1 show2 show3 show4
function notEnumerate(obj){
if(!Object.keys) return
var all = Object.getOwnPropertyNames(obj)
var enumerable = Object.keys(obj)
var arr = []
all.forEach((item) => {
if(enumerable.indexOf(item) == -1) {
arr.push(item)
}
})
return arr
}
var o = Object.getPrototypeOf(targetObj); // 跳过遍历自身属性,直接从原型上开始
var k=[],p;
for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
return k;
网友评论