Why does creating objects with constructor execute object's method in javascript? -
suppose want have 3 objects of type room. 3 objects bedroom, livingroom , bathroom. room has 2 properties length , breadth, , 1 method myfunc. use constructor method create 3 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 when run script myfunc gets executed 3 times displaying alert. thought since new keyword converts function object must not execute object's method -- typeof new room returns "object".
my question is:
if statement
new room();converts copy ofroom()function object isn't equvalent object creation literal notation? if yes shouldn'tvar bedroom = new room();assign properties of room object bedroom object? why execute objects method?how create objects without executing methods?
alert function , alert() executes it. has nothing how objects created.
keep in mind alert needs wrapped because written in native code foreign javascript.
so should (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 bedroom.'); edit:
the main reason alert expects this bound window. meaning following 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 bedroom.');
Comments
Post a Comment