如何创建Prototype函数可访问的私有变量?

buz*_*ord 15 javascript prototypal-inheritance

我试图深入了解原型继承和类创建(我知道,还有其他方法,但为了这个目的,我试图掌握原型.)我的问题是:使用下面的代码示例,是有没有办法内部创建私有变量Tree,并Fruit不会与该函数返回,但仍是原型函数访问genusbulk

var Tree = function ( name, size ) { 
    this.name = name;
    this.size = size;
};

Tree.prototype.genus = function(){
    return ((typeof this.name !== 'undefined') ? this.name : 'Hybridicus Maximus');
};
Tree.prototype.bulk = function(){
    return ((typeof this.size !== 'undefined') ? this.size : '8') + ' ft';
};


var Fruit = function( name, size ) { 
    this.name = name;
    this.size = size;
};

Fruit.prototype = new Tree();
// Fruit.prototype = Tree.prototype; -- I know this can be used, too.

Fruit.prototype.bulk =  function(){
    return ((typeof this.size !== 'undefined') ? Math.floor(this.size / 2) : '4') + ' lbs';
};

var pine = new Tree('Pine', 9);
var apple = new Fruit('Apple', 6);

console.log(pine.genus(), pine.bulk()); // Outputs: "Pine 9 ft"
console.log(apple.genus(), apple.bulk()); // Outputs: "Apple 3 lbs"
Run Code Online (Sandbox Code Playgroud)

编辑:我试图取代this.name,并this.size与在原型函数访问私有变量.抱歉缺乏清晰度!

Poi*_*nty 14

是.你可以这样做:

(function() {
  var private = "hi";

  Tree.prototype.genus = function(){
    return ((typeof this.name !== 'undefined') ? this.name : 'Hybridicus Maximus');
  };
  Tree.prototype.bulk = function(){
    return ((typeof this.size !== 'undefined') ? this.size : '8') + ' ft';
  };
})();
Run Code Online (Sandbox Code Playgroud)

现在,这将提供这些函数可以看到的私有变量,但它将是一个私有的"类"变量 - 换句话说,所有实例将共享相同的变量.如果你想要每个实例的一个私有变量,你必须在构造函数(或"init"方法,或其他)中这样做,这意味着必须在那里创建共享这些私有的方法.(你当然可以在原型上放置一个函数,它将在构造时创建实例方法.)

编辑 - 你可以做的一件事是使用这样的技术来构建像jQuery的".data()"这样的机制,这样你就有了一个类变量作为保存每个实例值的地方.它有点笨重,但它是可行的.