【发布时间】:2020-12-18 04:17:11
【问题描述】:
我可以在构造函数中使用变量而不在函数参数中使用它吗?
如下所示:
function Person(name,height,weight){
this.name=name;
this.height=height;
this.weight=weight;
this.bmi=null;
this.calculateBMI = function()
{
if (this.bmi===null){
this.bmi = this.weight / (Math.pow(this.height,2));
}
return this.bmi;
}
}
var person1 = new Person("alayna",23, 56)
我可以有函数 Person(name, height, weight),在里面我有 this.bmi 吗?函数怎么知道这里的bmi是什么?
【问题讨论】:
-
是的,您也可以有其他函数范围的变量,即使用
var、let、const等定义,没有什么可以限制构造函数中的变量使用/定义 -
构造函数没有什么特别之处,只是当你使用
new时它们会被自动调用。构造函数可以对对象做任何其他方法可以做的事情。 -
你是在问能不能做
var bmi = null; this.calculateBMI = function() { if (bmi===null)...
标签: javascript