1

我想在 javasript 中实现类似的东西:

var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);

请问我该怎么做(试图弄乱功能prototype但取得了一点成功)?

4

3 回答 3

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"
于 2012-07-10T07:35:55.873 回答
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,
    ...
};

如果您的库正确实现了“扩展”功能(构造函数没有什么特别的),这也应该有效:

Object.extend(Hat, {
    Color: {RED: "F00", GREEN: "0F0", ...},
    Size: = {MEDIUM: 0, LARGE: 1, ...},
});
于 2012-07-10T07:36:10.710 回答
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
}
于 2012-07-10T07:45:46.763 回答