我试图更深入地掌握原型继承和类创建(我知道,还有其他方法,但为此我试图掌握原型。)我的问题是:使用下面的代码示例,是有一种方法可以在内部创建私有变量,Tree
并且Fruit
不会与函数一起返回,但原型函数仍然可以访问genus
和bulk
?
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"
编辑:我正在尝试用可以在原型函数中访问的私有变量替换this.name
和。this.size
很抱歉没有说清楚!