简体   繁体   中英

How does the Error object seems to create properties on itself by his own on Javascript?

Ok I'd first like to say that I know there's probably a very basic explanation for this, so excuse me if this is a way too newbie kind of question.

The question is: How come the Error.message property doesn't exist until I create a new prototype?

Example:

let a = new Error('testing')
console.log( a.message ) // 'testing'

But before if I tried to access the Error properties and methods (eg: Object.getOwnPropertyNames(Error) ) the message property wouldn't even be there, not even an empty string, it just wouldn't exist.

Shouldn't it have been an empty string before? How does the Error object creates a new property on its own when a new prototype is created?

getOwnPropertyNames only returns properties set on an object , not inherited (prototype) properties. The clue is in the name: " own "-properties.

By example:

const a_simple_object_with_no_prototype = {
    b: "b",
    c: "c"
};

console.log( Object.getOwnPropertyNames( a_simple_object_with_no_prototype ) )
// [ "b", "c" ]

With an object with properties inherited from a prototype we get different results:

const an_object_used_as_a_prototype = {
    a: 789
};

function ConstructorFunction() {
    this.b = "b";
}
ConstructorFunction.prototype = an_object_used_as_a_prototype;

const an_object_with_a_prototype = new ConstructorFunction();
an_object_with_a_prototype.c = "c";


console.log( Object.getOwnPropertyNames( an_object_with_a_prototype ) )
// [ "b", "c" ] // does not include "a" which is inherited from the prototype

But before if I tried to access the Error properties and methods (eg: Object.getOwnPropertyNames(Error) ) the message property wouldn't even be there, not even an empty string, it just wouldn't exist.

That's because Object.getOwnPropertyNames(Error) will only list the "static" 1 members of the Error constructor function. If you do Object.getOwnPropertyNames( Error.prototype ) then you'll see them:

const protoProps = Object.getOwnPropertyNames( Error.prototype );
console.log( protoProps ); // ["constructor", "name", "message", "toString"]

I do note that the Error object in JavScript is imbued with some special behaviour which you cannot replicate in JavaScript itself, such as how its stack property works, but that's outside the scope of your question.

1 : I use the term "static" in the C++ / Java / C# sense in that it's a field/member that is associated with a type rather than an instance . It does not mean the property/field/member is unchanging, readonly, nor immutable.

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