"类“;常量和构造函数:如何实现

"Class" constants and constructor: how to implement?

本文关键字:何实现 实现 构造函数 quot 常量      更新时间:2023-09-26

我想在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
}