2012-09-30 37 views
0

我使用dojo 1.8作爲javascript庫。 我正在嘗試爲我的一個項目創建一個小的Vector類。使用dojo 1.8創建類聲明

我創建了一個函數克隆來克隆矢量對象。這裏是我的課「的TD /矢量」

define([ 
    'dojo/_base/declare', 
    'td/Vector' 
], function(declare, Vector) { 
return declare(null, { 

    x: null, 
    y: null, 

    constructor: function(x, y) { 
     this.x = x; 
     this.y = y; 
    }, 

    clone: function() { 
     return new Vector(this.x, this.y); 
    }, 

    length: function() { 
     return Math.sqrt((this.x * this.x) + (this.y * this.y)); 
    }, 

    normalize: function() { 
     var length = this.length(); 
     this.x = this.x/length; 
     this.y = this.y/length; 
    }, 

    distance: function(target) { 
     return new Vector(target.x - this.x, target.y - this.y); 
    } 
}); 
}); 

現在我的問題:

變量「矢量」是一個空的對象。

那麼我該如何做這樣的事情。在JavaScript中是否存在類似PHP中的「self」?在課堂上創建自我的新實例的正確方法是什麼?

+0

我也嘗試「新的自()」,但自我引用窗口對象 – dattn

回答

2

Vector變量是td/Vector模塊的返回值,即td/Vector.js文件,而不是您上面的類declare,這應該是它是空對象的原因。

要引用的類本身:

define(["dojo/_base/declare"], function(declare) { 

    var Vector = declare(null, {  

     constructor: function(x, y) { 
      this.x = x; 
      this.y = y; 
     }, 

     clone: function() { 
      return new Vector(this.x, this.y); 
     } 
    }); 

    return Vector; 

}); 

在的jsfiddle看到它在行動:http://jsfiddle.net/phusick/QYBdv/