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?