1
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 ??

dfsq
  • 182,609
  • 24
  • 222
  • 242
Vino
  • 304
  • 1
  • 3
  • 11
  • possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – user2864740 Jul 10 '15 at 06:54

1 Answers1

2

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();
dfsq
  • 182,609
  • 24
  • 222
  • 242