简体   繁体   English

在 JavaScript Object 中创建然后创建属性的 function 有什么意义?

[英]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!我是 JS 新手,目前在对象/方法部分!

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.控制台日志的预期结果是 19,这正是我得到的。 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:尽你所能,要打印出“年龄:19”,我们首先需要写:

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.就像,我很确定您可以简单地创建一个年龄属性并在那里编写 function 来做与我们在这里所做的相同的事情,但是通过调用 function 的额外步骤,然后控制台记录它生成的属性。

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: Ciao,一个 object 使用像你这样的方法:

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:和 object 没有这样的方法:

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:让我稍微改写一下你的 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 .如您所见,现在我将当前年份作为 function CalcAge的参数传递。 What's the difference between the 2 solutions?两种解决方案有什么区别? First one is static ( age: 19 ) and next year will be no more valid.第一个是 static( age: 19 ),明年将不再有效。 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.因此,您的解决方案(稍作修改)变得更加灵活,可以永远使用。

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

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