user31782
user31782

Reputation: 7589

Why does creating objects with constructor execute object's method in javascript?

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:

Upvotes: 0

Views: 197

Answers (3)

timolawl
timolawl

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.');


Edit:

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

or hor
or hor

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

buddy123
buddy123

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

Related Questions