Javascript - 不能实例化同一对象的多个实例

Javascript - 不能实例化同一对象的多个实例

问题描述:

我想实例化同一对象的多个实例。第一个实例工作正常,但是当我尝试初始化另一个对象,我得到这个错误,Javascript - 不能实例化同一对象的多个实例

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

这里是fiddle,这里是我的代码:

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

综上所述,我的目标是实例化同一个“类”的多个实例。

您正在重新定义halo cunstructor:

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

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

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

+0

难道不应该被'返回新'晕'的底部绘制'? – FakeRainBrigand 2013-03-22 05:51:11

+0

不是,在这种情况下,这不是我们所需要的。 'return draw'就好像它是'return {width:function(){},height:function(){}}'一样。 – dfsq 2013-03-22 06:00:21

+0

啊,对不起。你是对的。我在想原型。 – FakeRainBrigand 2013-03-22 06:01:14

我建议结构性的东西多一点这样的:

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

你为什么这么说?这样做会有什么好处,而不是我现在这样做的方式? – John 2013-03-22 08:38:48

+1

@约翰,这是做类似事物的标准方式。它可以让其他人更好地理解你的代码,并且可以更容易地将其合并到其他代码中。例如,如果您以后决定继承,这可以让您使用现有的框架,教程和指南。你不需要这样做,它只是普遍的首选(为什么我对你的代码感到困惑)。 – FakeRainBrigand 2013-03-25 13:47:22

+0

好的,理解。感谢您花时间解释这一点。你不会知道这个话题有什么好的学习资源,对吗?我可以只是谷歌,但是那里有不少文章,都说明他们的方法是最好的,而且很难辨别出遵循哪个“标准”。 :/ – John 2013-03-27 06:38:04