简体   繁体   中英

What is the point of creating a function in JavaScript Object that then creates property?

(Sorry for my bad English)

I am new to JS and currently on the Object/method part!

I've just written this pieces of code:

var jason = {
  fname: 'jason',
  lname: 'roy',
  yearBorn: 2001,
  CalcAge: function () {
    this.age = 2020 - this.yearBorn;
  }
};
jason.CalcAge();
console.log(jason.age);

The expected result on console log is 19 and that's exactly what I'm getting. But that's not my question.

My question is what is the point of going through such a long process just to create an age property?

AS you can, to print out the "age: 19" we first need to write:

jason.CalcAge();

And then,

console.log(jason.age);

Dont you guys think its kinda useless?

Like, I'm pretty sure you can simply create an age property and write function there to do the same thing as we're doing here but by doing an extra step of calling a function and then console logging the property it generates.

Once again, sorry for my bad English and let me know if you guys didn't get me!

Ciao, an object with a method like yours:

var jason = {
  fname: 'jason',
  lname: 'roy',
  yearBorn: 2001,
  CalcAge: function () {
    this.age = 2020 - this.yearBorn;
  }
};
jason.CalcAge();
console.log(jason.age);

And and object without a method like this:

var jason = {
  fname: 'jason',
  lname: 'roy',
  yearBorn: 2001,
  age: 19
};
console.log(jason.age);

seems similar but are totally different. Why? Flexibility . Let me rewrite a little bit your object:

var jason = {
   fname: 'jason',
   lname: 'roy',
   yearBorn: 2001,
   CalcAge: function (currYear) {
      this.age = currYear - this.yearBorn;
   }
};
jason.CalcAge(2020);
console.log(jason.age);

As you can see, now I'm passing the current year as parameter of function CalcAge . What's the difference between the 2 solutions? First one is static ( age: 19 ) and next year will be no more valid. Second one allows you to calculate age in any year you want (not only current year). So your solution (with a little modification) becames more flexible and could be used forever.

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