简体   繁体   中英

why Object.keys(Array.prototype) returns empty array?

Following this code first:

function User(name, dept){
    this.username = name;
    this.dept = dept;
    this.talk = function(){
        return "Hi";
    };
}

function Employee(){
    User.apply(this, Array.prototype.slice.call(arguments));
}

Employee.prototype = new User();


for(var x in Employee.prototype) 
    console.log(x, ':', Employee.prototype[x]);

Object.keys(Employee.prototype);//prints array of keys...

It prints out fine...

Array.prototype; //[]
Array.prototype.slice; // Function

var o = Array.prototype;

for(var i in o) console.log(i, ':', o[i]); //it doesn't execute
Object.keys(Array.prototype); //[] - ???

How to explain this behaviour?

Can we mimic this for constructors we try to create?

Object.keys() - MDN

The Object.keys() method returns an array of a given object's own enumerable properties...

We can check whether a given property is enumerable:

Array.prototype.propertyIsEnumerable('push');
// false

Alternatively we can get a full descriptor for the object's property, which will also include the enumerability flag.

Object.getOwnPropertyDescriptor(Array.prototype, 'push');
// {writeable: true, enumerable: false, configurable: true}

The properties on Array.prototype are deliberately non-enumerable so that they don't show up in for...in loops .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM