2014-01-28 46 views
0

我想要的是將多個同一對象傳遞給該對象的函數 我正在嘗試製作一個自定義矢量數學助手。在javascript中傳遞多個對象作爲參數

我所尋找的是類似

function dotProduct(Vector3 a, Vector3 b){ 
    //do calculations here 
    return Vector3 a.b; 
} 

但我似乎無法找到任何幫助。 有什麼想法?

+3

JavaScript沒有類型提示,一切都是動態的。 – elclanrs

+1

你能否澄清一下問題是什麼,我有點不確定你的問題。 (除非它是上面的,在這種情況下elclanrs是正確的) – Carl

+0

你能否提供一個vector3對象的樣本 – Charlie

回答

3

JavaScript沒有類或提示提示。你可以這樣做:

var Vector3 = function(x, y, z) { 
    this.x = x; 
    this.y = y; 
    this.z = z; 
} 

var dotProduct = function(a, b) { 
    // do something with a.x, a.y, a.z, b.x, b.y, b.z 
    return new Vector3(...); 
} 

要創建一個新Vector3,您可以使用new關鍵字:

//     x y z 
var v1 = new Vector3(1, 2, 3); 
var v2 = new Vector3(2, 3, 4); 
var product = dotProduct(v1, v2); 

您還可以添加上Vector3實例dotProduct()功能:

Vector3.prototype.dotProduct = function(b) { 
    // do something with this.x, this.y, this.z, b.x, b.y, b.z 
    return new Vector3(...); 
} 

在這種情況下,您可以將其稱爲:

var v1 = new Vector3(1, 2, 3); 
var v2 = new Vector3(2, 3, 4); 
var product = v1.dotProduct(v2); 

爲了讓您的意圖明顯,你可以添加註釋類型提示:

/** 
* @param Number x 
* @param Number y 
* @param Number z 
* @constructor 
*/ 
var Vector3 = function(x, y, z) { 
    this.x = x; 
    this.y = y; 
    this.z = z; 
} 

/** 
* @param Vector3 b 
* @return Vector3 
*/ 
Vector3.prototype.dotProduct = function(b) { 
    // do something with this.x, this.y, this.z, b.x, b.y, b.z 
    return new Vector3(...); 
} 

大多數JavaScript的IDE都知道這意味着什麼,並會幫助你的時候你不發出警告通過Vector3 s作爲參數。

相關問題