Get instantiated object's own properties

hasOwnProperty () method returns a Boolean value indicating that the object itself attribute has the specified attributes (i.e., whether there is a specified key)

This method belongs to Objectthe object, since all objects are "inherited" the object instance of Object, so almost all instances of objects can use this method.

grammar

obj.hasOwnProperty(prop)

parameter

return value

Used to determine whether an object has a specified property Boolean.

o = new Object();
o.prop = 'exists';

function changeO() {        // 改变对象自身属性
  o.newprop = o.prop;
  delete o.prop;           
}

o.hasOwnProperty('prop');   // 返回 true
changeO();
o.hasOwnProperty('prop');   // 返回 false
o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');             // 返回 true       hasOwnProperty只能获得自身属性,不能获得继承属性
o.hasOwnProperty('toString');         // 返回 false
o.hasOwnProperty('hasOwnProperty');   // 返回 false

Object.getOwnPropertyNames () method returns a specified object owned by itself attribute name attribute (not including but not enumerated attribute value for the attribute name Symbol) consisting of an array .

grammar

Object.getOwnPropertyNames(obj)

parameter

  • obj

    An object itself and not enumerable enumerated attribute name is returned.

return value

String array corresponding to own property found on a given object.

var arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"]

// 类数组对象
var obj = { 0: "a", 1: "b", 2: "c"};
console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"]

// 使用Array.forEach输出属性名和属性值
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  console.log(val + " -> " + obj[val]);
});
// 输出
// 0 -> a
// 1 -> b
// 2 -> c

//不可枚举属性
var my_obj = Object.create({}, {
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});
my_obj.foo = 1;

console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]

Not only to obtain enumerated property

The following example uses the Array.prototype.filter()method, (all available from the array of property names Object.getOwnPropertyNames()obtaining method) can be removed enumerated attributes (using the Object.keys()method to obtain), the remaining attributes of the property is not enumerable:

var target = myObject;
var enum_and_nonenum = Object.getOwnPropertyNames(target);
var enum_only = Object.keys(target);
var nonenum_only = enum_and_nonenum.filter(function(key) {
    var indexInEnum = enum_only.indexOf(key);
    if (indexInEnum == -1) {
        // 没有发现在enum_only健集中意味着这个健是不可枚举的,
        // 因此返回true 以便让它保持在过滤结果中
        return true;
    } else {
        return false;
    }
});

console.log(nonenum_only);
注:Array.filter(filt_func)方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

algorithm

Guess you like

Origin www.cnblogs.com/danew/p/11511952.html