admin管理员组

文章数量:1278851

I am trying to instantiate multiple instances of the same object. The first instantiation works fine, but when I try to initialize another object, I get this error,

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

here is the fiddle, and here is my code:

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

In summary, my objective is to instantiate multiple instances of the same "class".

I am trying to instantiate multiple instances of the same object. The first instantiation works fine, but when I try to initialize another object, I get this error,

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

here is the fiddle, and here is my code:

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

In summary, my objective is to instantiate multiple instances of the same "class".

Share Improve this question asked Mar 22, 2013 at 5:37 JohnJohn 2651 gold badge3 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

You are redefining halo cunstructor:

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

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

Fixed version: http://jsfiddle/GB4JM/1/

I would suggest something structured a little more like this:

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

本文标签: oopJavascriptCannot instantiate multiple instances of the same objectStack Overflow