“class”中的嵌套函数
问题描述:
function Fruits() {
this.Banana = function() {
this.getColor = function(){
return 'yellow';
};
};
this.Apple= function() {
this.getColor = function(){
return 'red';
};
};
}
var apple = new Fruits.Apple();
console.log(apple.getColor());
这不起作用。我在这里错过了什么?这是嵌套方法的“类”的错误方法?“class”中的嵌套函数
由于使用
答
一些好奇心:
var a = new new Fruits().Apple
顺便说一句。也许你想创建一个类似静态类的东西?
var Fruits = {
Apple:function() {
this.getColor = function(){
return 'red';
};
},
Banana: function() {
this.getColor = function(){
return 'yellow';
};
}
}
然后它会工作。
var apple = new Fruits.Apple();
console.log(apple.getColor());
答
尝试:
var apple = new Fruits();
apple.Apple();
console.log(apple.getColor());
答
您需要首先实例水果。从我的控制台...
var f = new Fruits()
undefined
new f.Apple()
Fruits.Apple
new f.Apple().getColor()
"red"
答
这是静态属性和实例属性之间的差异。 正如你宣布苹果是水果的一个实例属性,你必须实现一个水果来允许一个苹果实例化,苹果的crontructor将是一种水果的方法。 如果你想静态类,你所要做的
function Fruits() {
}; Fruits.Apple =函数(){
this.getColor = function(){
return 'red';
};
};
是的,这将是完美的。谢谢! – Johan 2012-08-11 13:54:02