我想在javascript中实现类似的东西:
var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
我怎么能这样做(试图弄乱函数prototype
但是稍微成功一点)?
答案 0 :(得分:6)
如果你创建一个Hat
构造函数,你可以这样做:
function Hat(color, size) {
this.color = color;
this.size = size;
}
Hat.Color = {
RED: "#F00",
GREEN: "#0F0",
BLUE: "#00F"
};
Hat.Size = {
SMALL: 0,
MEDIUM: 1,
LARGE: 2
}
然后,您可以创建new Hat
并获取其属性
var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
var hatColor = hat.color; // "#F00"
答案 1 :(得分:5)
Hat
将是一个构造函数:
function Hat(color, size) {
this.id = "X"+color+size; // or anything else
}
在原型上是Hat
个实例的“方法”:
Hat.prototype.raise = function() {
...
};
但常量是Function对象的属性:
Hat.Color = {
RED: "F00",
GREEN: "0F0",
...
};
Hat.Size = {
MEDIUM: 0,
LARGE: 1,
...
};
如果你的库正确地实现了“extend”函数(在构造函数上没有什么特别之处),那么这也应该有效:
Object.extend(Hat, {
Color: {RED: "F00", GREEN: "0F0", ...},
Size: = {MEDIUM: 0, LARGE: 1, ...},
});
答案 2 :(得分:1)
这是功能继承方式。它区分私有和公共方法和变量。
var Hat = function (color, size) {
var that = {};
that.Color = { RED: 'abc'}; // object containing all colors
that.Size = { Medium: 'big'}; // object containing all sizes
that.print = function () {
//I am a public method
};
// private methods can be defined here.
// public methods can be appended to that.
return that; // will return that i.e. all public methods and variables
}