Vino
Vino

Reputation: 304

If I try to access a property which is not defined or inherited, its returning empty string. Why such behaviour?

function x() {
    console.log(this.name); 
}
x();

on executing , console.log will give an empty string.

Is the JavaScript assigns empty value to any property which is not defined or inherited ??

Upvotes: 1

Views: 41

Answers (1)

dfsq
dfsq

Reputation: 193311

Since you are are using function without new keyword (not as constructor) this points to global object which is window. And window.name is predefined property identifier, typically empty string by default.

If you used constructor function instead (and you should because your intention is to use own/inherited properties with this), your code would have acted as expected giving you undefined result:

function x() {
    console.log(this.name); // => is indeed "undefined"
}
new x();

Upvotes: 2

Related Questions