how to access javascript object variables in prototype function -


i have following javascript

function person() {   //private variable   var fname = null;   var lname = null;    // assign value private variable   fname = "dave";   lname = "smith"; };  person.prototype.fullname = function () {   return this.fname + " " + this.lname; };  var myperson = new person(); alert(myperson.fullname()); 

i trying understanding of object orientated techniques in javascript. have simple person object , added function prototype.

i expecting alert have "dave smith", got "underfined underfined". why , how fix it?

unfortunately can't access private variable. either change public property or add getter/setter methods.

function person() {      //private variable     var fname = null;     var lname = null;      // assign value private variable     fname = "dave";     lname = "smith";      this.setfname = function(value){ fname = value; };     this.getfname = function(){ return fname; } }; 

see javascript - accessing private member variables prototype-defined functions


but looks looking for: javascript private member on prototype

from post:

as javascript lexically scoped, can simulate on per-object level using constructor function closure on 'private members' , defining methods in constructor, won't work methods defined in constructor's prototype property.

in case:

var person = (function() {     var store = {}, guid = 0;      function person () {         this.__guid = ++guid;         store[guid] = {              fname: "dave",             lname: "smith"         };     }      person.prototype.fullname = function() {         var privates = store[this.__guid];         return privates.fname + " " + privates.lname;     };      person.prototype.destroy = function() {         delete store[this.__guid];     };      return person;  })();   var myperson = new person();  alert(myperson.fullname());  // in end, destroy instance avoid memory leak myperson.destroy(); 

check out live demo @ http://jsfiddle.net/roberkules/xurhu/


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

android - layout with fragment and framelayout replaced by another fragment and framelayout -