OOP in Javascript: questions about classes, attribs, and builder functions -



OOP in Javascript: questions about classes, attribs, and builder functions -

i trying utilize oop in javascript. have 2 questions respect this: have found unusual behavior in code:

function apple(pparam){ this.var1 = "default value"; this.init = function(){var1 = pparam;}; this.getvalue = function(){return var1;}; } obj = new apple("new value"); obj.init(); alert(obj.getvalue()); //returns 'new value' alert(obj.var1); //returns 'default value'

i expected same result in both alerts these different... likes 'var1' has different interpretation if called variable or getter function.

other question: how can implement "init" function builder, implicitly?? (as c++ or java)

thanks!!

try 1 time again with

function apple(pparam){ this.var1 = "default value"; this.init = function(){this.var1 = pparam;}; this.getvalue = function(){return this.var1;}; }

note: this. in init , getvalue.

if {var1 = pparam;} out this, javascript tries find local variable name var1, not find one. javascript seek , find in global scope, still not find it. create variable in global scope (window global scope if in web browser). similar in getvalue function javascript find var1 in global scope unless tell in this.

have @ http://jsfiddle.net/486qh6qw/ illustration of this.

in reply sec part of question have 2 options. either in function apple (which think thinking of class declaration) such:

function apple(pparam){ this.var1 = "default value"; this.getvalue = function(){return this.var1;}; this.var1 = pparam; // can set arbitrary code here example: if(this.var1 === 'blue') { this.isblue = true; } else { this.isblue = false; } };

the other alternative phone call init function apple function

function apple(pparam){ this.var1 = "default value"; // init function should not called outside function // can hide making local variable. var init = function(apple){apple.var1 = pparam;}; this.getvalue = function(){return this.var1;}; init(this); };

javascript function class

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -