I was playing around with javascript in my web browser when I noticed something strange.
I defined a class TestClass like this:
class TestClass{};
var testObj=new TestClass();
Object.setPrototypeOf(testObj, null);
When I console.log
ed testObj, there were no properties.
Here is where I became confused.
typeof testObj
returned "object"
. But when I ran the following:
Object.prototype.testProperty='testing';
testObj
didn't have the property testProperty
, even though I'd defined it for all objects and according to typeof
, testObj
was an object.
Why is this happening? Don't all values inherit properties from Object
?
This also happens for [[Scopes]]
objects. When, in chrome, I console.log
a function and I save its [[Scopes]]
property as a global variable, typeof
returns "object"
but the global variable does not have the property testProperty
.
Don't all values inherit properties from
Object
?
No. Most objects inherit from Object.prototype
, but some don't - like the Object.prototype
object itself. Also objects whose prototype was explicitly set to null
, like the testObj
one you created in your code or a Object.create(null)
. Other cases are objects from different realms, which inherit from a different Object.prototype
object.