繁体   English   中英

Javascript对象构造函数参数

[英]Javascript object constructor function arguments

我可以在构造函数中有一个变量而没有在函数参数中吗?

像下面这样:

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 是什么?

您可以选择是否使用参数的值

function Person (name, height, weight) {
  this.name = name;
  this.height = height;
  this.weight = weight;
  this.bmi = this.weight / (Math.pow(this.height, 2));
}

Person.prototype.calculateBMI = function() {
  this.bmi = this.weight / (Math.pow(this.height, 2));
  return this.bmi;
}

var person1 = new Person("alayna",23, 56);

虽然,也许你想看看 getter 和 setter: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

这将允许您在每次更新heightweight时更新bmi 例如,如果heightweight发生变化,以下将更新bmi

class Person {
  constructor(name, height, weight) {
    this.name = name;
    this._height = height;
    this._weight = weight;
    this.bmi = this._weight / (Math.pow(this._height, 2));
  }
  
  get weight() {
    return this._weight;
  }
  
  set weight(value) {
    this._weight = value;
    this.bmi = value / (Math.pow(this._height, 2));
  }
  
  get height() {
    return this._height;
  }
  
  set height(value) {
    this._height = value;
    this.bmi = this._weight / (Math.pow(value, 2));
  }
}

const person1 = new Person('alayna', 23, 56);
console.log(person1.bmi);
person1.height = 25;
console.log(person1.bmi);

暂无
暂无

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

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