Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  47] [ 6]  / answers: 1 / hits: 20507  / 13 Years ago, fri, july 22, 2011, 12:00:00

I have the following javascript



function person() {
//private Variable
var fName = null;
var lName = null;

// assign value to private variable
fName = Dave;
lName = Smith;
};

person.prototype.fullName = function () {
return this.fName + + this.lName;
};

var myPerson = new person();
alert(myPerson.fullName());


I am trying to get an understanding of object orientated techniques in javascript. I have a simple person object and added a function to its prototype.



I was expecting the alert to have Dave Smith, however I got underfined underfined. why is that and how do I fix it?


More From » javascript

 Answers
7

Unfortunately you can't access a private variable. So either you change it to a public property or you add getter/setter methods.



function person() {

//private Variable
var fName = null;
var lName = null;

// assign value to private variable
fName = Dave;
lName = Smith;

this.setFName = function(value){ fName = value; };
this.getFName = function(){ return fName; }
};


see javascript - accessing private member variables from prototype-defined functions






But actually this looks like what you are looking for:
Javascript private member on prototype



from that SO post:




As JavaScript is lexically scoped, you can simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.




in your 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 the end, destroy the instance to avoid a memory leak
myPerson.destroy();


Check out the live demo at http://jsfiddle.net/roberkules/xurHU/


[#91065] Wednesday, July 20, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kendellc

Total Points: 84
Total Questions: 97
Total Answers: 102

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
;