未传递期望值时在功能上设置默认值

问题描述

我想为没有传递任何功能的情况(例如: var v = Vector(),而不是Vector(2,5,1)

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

if (Vector3() === null)
{
   this.x = 0;
   this.y = 0;
   this.z = 0;
}

解决方法

您可以使用默认参数,如果不通过默认参数,则默认为0:

function Vector(x=0,y=0,z=0) {
  this.x = x;
  this.y = y;
  this.z = z;
}
console.log(new Vector(2,5,1));
console.log(new Vector());