Javascript - 无法实例化同一对象的多个实例

Joh*_*ohn 2 javascript oop

我试图实例化同一对象的多个实例.第一个实例化工作正常,但是当我尝试初始化另一个对象时,我收到此错误,

Uncaught TypeError: Object #<draw> has no method 'width'

这是小提琴,这是我的代码:

function halo() {
  var width = 720, // default width
      height = 80; // default height

  function draw() {
    // main code
    console.log("MAIN");
  }

  draw.width = function(value) {
    if (!arguments.length) return width;
    width = value;
    return draw;
  };

  draw.height = function(value) {
    if (!arguments.length) return height;
    height = value;
    return draw;
  };

  return draw;
}

var halo = new halo();
halo.width(500);

var halo2 = new halo();
halo2.width(300);
Run Code Online (Sandbox Code Playgroud)

总之,我的目标是实例化同一"类"的多个实例.

dfs*_*fsq 8

您正在重新定义halocunstructor:

var halo = new halo(); // <-- change variable name to halo1
halo.width(500);

var halo2 = new halo();
halo2.width(300);
Run Code Online (Sandbox Code Playgroud)

修正版:http://jsfiddle.net/GB4JM/1/