简体   繁体   中英

Javascript object constructor function arguments

Can I have a variable in a constructor fuction without having it in the function argument?

like this below:

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)

can I have function Person(name, height, weight), and inside it I have this.bmi? how does the function know what is bmi here?

You can choose whether to use the value of a parameter or not

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);

Although, perhaps you want to look at getters and setters: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

Which will allow you to update bmi every time height or weight is updated. For example the following will update the bmi if either height or weight ever changes

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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