最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "Class" constants and constructor: how to implement? - Stack Overflow

programmeradmin0浏览0评论

I would like to have something like this implemented in javasript please:

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

How can I do it please (tried to mess with function prototype but with a little success)?

I would like to have something like this implemented in javasript please:

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

How can I do it please (tried to mess with function prototype but with a little success)?

Share Improve this question edited Jul 10, 2012 at 7:35 Alexander Abramovich asked Jul 10, 2012 at 7:30 Alexander AbramovichAlexander Abramovich 11.5k26 gold badges74 silver badges113 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

You can do that if you create a Hat constructor function like this:

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
}

You can then create a new Hat and get its properties

var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
var hatColor = hat.color; // "#F00"

Hat will be a constructor function:

function Hat(color, size) {
    this.id = "X"+color+size; // or anything else
}

On the prototype are "methods" for Hat instances:

Hat.prototype.raise = function() {
    ...
};

But the constants are properties of the Function object:

Hat.Color = {
    RED: "F00",
    GREEN: "0F0",
    ...
};
Hat.Size = {
    MEDIUM: 0,
    LARGE: 1,
    ...
};

If your library implements the "extend" function correctly (nothing special on constructors), this should also work:

Object.extend(Hat, {
    Color: {RED: "F00", GREEN: "0F0", ...},
    Size: = {MEDIUM: 0, LARGE: 1, ...},
});

This is the functional inheritance way. It distinguishes between private and publci methods and variables.

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
}
发布评论

评论列表(0)

  1. 暂无评论