0

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?

  • related: [Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?](http://stackoverflow.com/q/13239317/1048572) – Bergi Feb 03 '16 at 15:48

2 Answers2

0

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
James Long
  • 4,629
  • 1
  • 20
  • 30
0

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • And static properties are not inherited? –  Feb 03 '16 at 15:48
  • I thought I just said they are not. ;-) – deceze Feb 03 '16 at 15:48
  • @Devashish: By child classes, yes, by instances, no. – Bergi Feb 03 '16 at 15:49
  • Seems like more interesting things are coming in my Js programming career. Thanks for help :) –  Feb 03 '16 at 15:50
  • 1
    @Devashish Really you need to understand what `new` does. In a nutshell, it transports the `.prototype` of the constructor function (`Foo`) to the new object (`f`). Whatever else was tacked onto `Foo` is irrelevant. – deceze Feb 03 '16 at 15:51