Reputation: 7589
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 of Room()
function into an object then isn't this equvalent to object creation with literal notation? If yes then shouldn't var 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?
Upvotes: 0
Views: 197
Reputation: 5564
alert
is the function and alert()
executes it. It has nothing to do with how objects are created.
Keep in mind that alert
needs to be wrapped because it is written in native code foreign to JavaScript.
So it should be (with clickable example):
function Room(len, bred, myFunc) {
this.len = 5;
this.bred = 8;
this.myFunc = function(x) {
alert(x)
};
}
var bedroom = new Room();
var livingroom = new Room();
var bathroom = new Room();
bedroom.myFunc('This is the bedroom.');
The main reason is that alert
expects this
to be bound to window
. Meaning that the following will also work:
this.myFunc = alert.bind(window);
function Room(len, bred, myFunc) {
this.len = 5;
this.bred = 8;
this.myFunc = alert.bind(window);
}
var bedroom = new Room();
var livingroom = new Room();
var bathroom = new Room();
bedroom.myFunc('This is the bedroom.');
Upvotes: 1
Reputation: 723
dont use brackets with alert. Brackets cause the alert to be executed. If you omit brackets, then a function alert will be assigned to your myFunc property.
Upvotes: 0
Reputation: 6307
You are executing the function during assignment, that is why you see three executions with that code. Simply replace your assignment to the function name itself:
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();
Upvotes: 0