星期四, 5月 30, 2013

[Javascript] 透過prototype的方法存取private member

記錄一下先前遇到的事情,
某一天在寫類別的時候,遇到想要用prototype去存取private member的成員,
就偷懶直接把private member改為public member XD,
查了一下Stackflow javascript - accessing private member variables from prototype-defined functions

No, there's no way to do it. That would essentially be scoping in reverse.
Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.
Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.
You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this object, which the prototype methods (along with everything else)will have access to.

function Dog(_dogName){
    var that = this;
    
    var dogname = _dogName || "dog" ;//default setting
  
    that._getName = function(){
       return dogname;
    };
    
    that._setName = function(newName){
         dogname = newName;
    };

};
//use getName to access private member
Dog.prototype.getName = function(){
    return  this._getName();
};
Dog.prototype.setName = function(newName){
    return  this._setName(newName);
};
    
var myDog = new Dog();
console.log("mydog:" + myDog.getName());

var tomDog = new Dog("tom");
console.log("tomDog:" + tomDog.getName());
tomDog.setName("mary");
console.log("tomDog2:" + tomDog.getName());


Fiddle看範例: Go

Reference:
Private Members in JavaScript

沒有留言:

張貼留言

留個話吧:)