I was watching the Douglas crockford video on javascript and one the thing that he mentioned was in case you forget to use new for class then it will populate the global namespace which in browser is window. I wanted to understand this better so I went and test this out as below
var User = function(first,last){
this.name = first + " " + last;
}
var user = new User("John","Resig");
alert(window.name); // expected to see undefined, but was John Resig
alert(user.name); // this should only show John Resig correctly
var user1 = User("Douglas","Crockford");
alert(window.name); // expected to see Douglas Crockford and shown correctly
There is two possibility now, either my understanding of global namespace is wrong or my example is wrong.
Appreciate if you could set me in the right direction.
The reason is
thisin theUserfunction refers towindowifnewisn’t used. The defaultthisfor a function (in traditional JavaScript[1]) iswindow.[1] Browsers which support
'use strict'won’t behave this way in strict mode. Instead they will throw an exception becausethisisundefinedifnew,apply,call,bind, etc. aren’t used. See http://jsfiddle.net/ufTq9/