简体   繁体   中英

Why some of the properties from the Object object are not inherited in sub-objects?

I found that 'keys' property was not inherited in my object, when testing the below code:

var obj = {x: 0, y:1};
console.log (Object.keys); //function

console.log (obj.keys); //undefined

So, my understanding is that some of the properties (in Object) are not inherited in user defined objects. Why? Are those properties only available through Object object? Is there any hack to get the properties list that are not available or inherited in user-defined objects?

Object.keys is a static property of the Object variable, obj.keys is a property og the obj variable, which would inherit from Object.prototype . You'd find this would work:

console.log(obj.hasOwnProperty); //function

Only the .prototype object is inherited as the prototype. Static class properties are not.

function Foo() {};
Foo.prototype.bar = function () {};
Foo.baz = function () {};

var f = new Foo();

f will have inherited bar , but not baz .

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