2

我正在尝试实例化同一对象的多个实例。第一次实例化工作正常,但是当我尝试初始化另一个对象时,我得到了这个错误,

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);

总之,我的目标是实例化同一“类”的多个实例。

4

2 回答 2

8

您正在重新定义halocunstructor:

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

var halo2 = new halo();
halo2.width(300);

固定版本:http: //jsfiddle.net/GB4JM/1/

于 2013-03-22T05:46:03.833 回答
4

我会建议一些结构更像这样的东西:

Halo = (function() {
  function Halo(width, height) {
    this.width = width || 720; // Default width
    this.height = height || 80; // Default height
  }

  Halo.prototype = {
    draw: function() {
      // Do something with this.width and this.height
    }
  };

  return Halo;
})();

var halo = new Halo(500, 100);
halo.draw();

var halo2 = new Halo(300, 100);
halo2.draw();
于 2013-03-22T06:04:07.623 回答