繁体   English   中英

在JavaScript中将多个对象作为参数传递

[英]Passing multiple objects as parameters in javascript

我想要的是将同一个对象的倍数传递给该对象的函数,而我正在尝试制作自定义矢量数学助手。

我正在寻找的是像

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

但是我似乎找不到任何帮助。 有什么想法吗?

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(...);
}

当您不将Vector3传递为参数时,大多数JavaScript IDE都会知道这意味着什么,并且会通过发出警告来帮助您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM