Suppose I want to have three objects of type Room. The three objects would be bedroom, livingroom and bathroom. Room has two properties length and breadth, and one method myFunc. I use constructor method to create the three required objects as:
function Room(len, bred, myFunc) {
this.len = 5;
this.bred = 8;
this.myFunc = alert();
}
var bedroom = new Room();
var livingroom = new Room();
var bathroom = new Room();
The problem is that when I run this script myFunc gets executed three times displaying the alert. What I thought was that since new keyword converts a function into an object it must not execute that object's method -- typeof new Room returns "object".
My question is:
if the statement
new Room();converts a copy ofRoom()function into an object then isn't this equvalent to object creation with literal notation? If yes then shouldn'tvar bedroom = new Room();just assign properties of Room object to bedroom object? Why does it execute objects method?How do I create objects without executing their methods?
alert()andalert. This has nothing to do with creating objects.alert? Does it replacealertwith it's definition?alertis a function, as isfunction(x) { alert(x); }. When you put parentheses after a function, the function gets executed:alert("foo")or(function(x) { alert(x); })("foo").thisis crucial; as is the fact that the difference between a function and a method is very flimsy.alertexpects to be called like a method (window.alert; the fact that it can be called asalertis because there is no local variablealert, andwindowis the default receiver). You definitely should finish the chapter on objects in JS...