2015-04-22 37 views
-1

我試圖實例化一個類是這樣的:試圖實例化一個動畫類,收到「對象不是一個函數」

var drawCrash = new DrawCrash; 

但我得到一個類型錯誤:對象不是一個函數。

我定義的類這樣的 -

var DrawCrash = { 
 

 
    //Private variables 
 
    canvas : ge1doot.Canvas(), 
 
    particles: "", 
 
    nbrParticles : 160, 
 
    speed : 6, 
 
    strength : .4, 
 
    radius : 4, 
 
    perspective : 0.5, 
 
    ang : null, 
 
    CosOrSin1 : null, 
 
    CosOrSin2 : null, 
 
    enum : { 
 
    \t Wobble : "wobble", 
 
    \t Twirl : "twirl" 
 
    }, 
 
    setDrawing : function (type) { 
 
    \t if (type === this.enum.Twirl){ 
 
    \t  Blah blah blah 
 
    \t \t this.cosOrSin2 = Math.sin; 
 
    \t } else if (type === this.enun.Wobble){ 
 
    \t \t Blah blah blah 
 
    \t } else {alert("Wrong enum for DrawCrash");} 
 
    }, 
 
    startDrawing : function() { 
 
    blah blah blah 
 
    } 
 
}

有什麼不對的語法?

+0

呀,DrawCrash不是一個函數的ñ,所以你不能新的。 –

回答

0

DrawCrash是一個普通的舊javascript對象(因此是錯誤):一個對象字面量。你訪問它的屬性和方法,簡單地說:

DrawCrash.startDrawing(); 

如果你想使用new操作符,那麼你需要創建一個函數:

function Car(make, model, year) { 
    this.make = make; 
    this.model = model; 
    this.year = year; 
} 

然後,你可以這樣說

var foo - new Car('plymouth', 'something', 1978); 

這裏有兩種方法有趣的討論:

Should I be using object literals or constructor functions?

1

這不是你如何在Javascript中實例化一個對象。

A「類」在這個世界上是一個簡單的函數:

function DrawCrash() { 

    //Private variables 
    var canvas = ge1doot.Canvas() 
    particles: "", 
    nbrParticles : 160, 
    speed : 6, 
    strength : .4, 
    radius : 4, 
    perspective : 0.5, 
    ang : null, 
    CosOrSin1 : null, 
    CosOrSin2 : null, 
    enum : { 
     Wobble : "wobble", 
     Twirl : "twirl" 
    }, 
    setDrawing : function (type) { 
     if (type === this.enum.Twirl){ 
     Blah blah blah 
     this.cosOrSin2 = Math.sin; 
     } else if (type === this.enun.Wobble){ 
     Blah blah blah 
     } else {alert("Wrong enum for DrawCrash");} 
    }, 
    startDrawing : function() { 
    blah blah blah 
    } 
} 

然後你就可以實例化它:

var drawCrash = new DrawCash(); 

但是所有的變量似乎是該對象私有。我要揭露一些公共,你需要把它們放在了「這個」:

function DrawCash() { 
    // private variables 
    var somePrivateVar = 42; 

    // public variables 
    this.publicVar = "hello"; 
} 

var drawcash = new DrawCash(); 
drawcash.publicVar; // returns "hello" 
drawcash.somePrivateVar; // undefined 

最後,爲了以有效的方式來定義這個「類」的方法,你需要來擴展對象原型(JavaScript是一種原型面向語言):

function DrawCash() { ... } 

DrawCash.prototype.someMethod = function() { ... } 

var drawcash = new DrawCash(); 
drawcash.someMethod(); 

你可以通過閱讀這篇文章,比如瞭解更多:

http://www.phpied.com/3-ways-to-define-a-javascript-class/

+0

ar duuuuuh!我現在明白了。謝謝! – Femtosecond

+0

太棒了!不要忘記接受或upvote的答案,如果它幫助你:) – floribon

+0

沒關係,我們走吧! – Femtosecond

相關問題