首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript -无法实例化同一对象的多个实例

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

Stack Overflow用户
提问于 2013-03-22 13:37:41
回答 2查看 6.7K关注 0票数 2

我正在尝试实例化同一对象的多个实例。第一个实例化运行良好,但是当我尝试初始化另一个对象时,我得到了这个错误,

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

下面是fiddle,下面是我的代码:

代码语言:javascript
复制
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);

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-22 13:46:04

您正在重新定义halo cunstructor:

代码语言:javascript
复制
var halo = new halo(); // <-- change variable name to halo1
halo.width(500);

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

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

票数 8
EN

Stack Overflow用户

发布于 2013-03-22 14:04:08

我建议使用更像这样的结构:

代码语言:javascript
复制
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();
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15563435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档