我想在 javasript 中实现类似的东西:
var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
请问我该怎么做(试图弄乱功能prototype
但取得了一点成功)?
我想在 javasript 中实现类似的东西:
var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
请问我该怎么做(试图弄乱功能prototype
但取得了一点成功)?
如果您创建这样的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"
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,
...
};
如果您的库正确实现了“扩展”功能(构造函数没有什么特别的),这也应该有效:
Object.extend(Hat, {
Color: {RED: "F00", GREEN: "0F0", ...},
Size: = {MEDIUM: 0, LARGE: 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
}