HTML and CSS Reference
In-Depth Information
The constructor implicitly returns the newly created object even though it has no return
statement. This p variable will therefore contain a reference to an object with the appropri-
ate name properties set.
If you omit the new keyword when calling a constructor function, it will act like any other
function. This is why constructor functions start with a capital letter by default: to remind
you to add the new keyword.
Omitting the new keyword is actually far worse than it may look. Inside the constructor
function you have access to a this variable that refers to the newly constructed object. If
you omit the new keyword this will refer to what it does in normal functions: the window
The window object is a global object within the browser that contains informa-
tion about the document. When JavaScript is used outside the browser an altern-
ative global object is provided in place of window .
This is a huge source of bugs because the code appears to work, but all instances of the
class will overwrite the same variables in the global namespace.
> p = Person('John', 'Smith');
The value of p is now undefined , since the function does not have a return value, but the
window object has had two new properties added to it:
> window.firstName
> window.lastName
This is one of the reasons I recommend against constructor functions except in controlled
environments such as the extends function.
Search WWH ::

Custom Search