首页 > 解决方案 > 未通过预期值时设置函数的默认值

问题描述

我想为函数没有传递任何内容的情况制作一个处理程序,例如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;
}

标签: javascriptfunctionnullundefined

解决方案


您可以使用默认参数,当它们未传递时默认为 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());


推荐阅读