简体   繁体   中英

Are there problems in this code? Can someone explain how this works

This code is from sololearn.com in the JS course.

function person(name, age) {
  this.name= name;  
  this.age = age;
  this.yearOfBirth = bornYear;
}
function bornYear() {
  return 2016 - this.age;
}

this.yearOfBirth = bornYear; why is bornYear just bornYear?

Shoudn't it be bornYear()

How does this even work?

I think this version would help you better to understand and is probably what the teacher wanted to write:

function Person(name, age) {
  this.name= name;  
  this.age = age;
  this.getYearOfBirth = function bornYear() {
    return 2016 - this.age;
  };
}

1- Always use Pascale case with a function that will be treated as class, that is why I renamed person to Person . That improves readability and confusions

2- I renamed yearOfBirth to getYearOfBirth , I agree the teacher should have given a better naming here too. Devs idiomatically use verbs to accessors (get/set) or methods (compute, parse, find...)

3- bornYear is a function within a class, so that an accessor is defined. Since bornYear is called without new operator, this will be equaled to window as default binding

Try it yourself, open your javascript console in the browser and type following:

function t() { console.log(this); }

t() returns window , the global/default scope

new t() returns a freshly created context t

bornYear is a function.

bornYear() is a value returned by burnYear function and equals 2016-this.age

What happens if this.yearOfBirth = bornYear

this.yearOfBirth = bornYear means you assign this.yearOfBirth=function(){return 2016-this.age}

Then lets say var me = new person("john",16) you can call me.yearOfBirth(); // 2000 me.yearOfBirth(); // 2000

What happens if this.yearOfBirth = bornYear() ,

while you are declaring var me = new person("john",16) bornYear() was executed return 2016-this.age but this.age is not defined so returned undefined. Then, this.yearOfBirth=undefined .

function person(name, age) {
  this.name= name;  
  this.age = age;
  this.yearOfBirth = bornYear;
}
function bornYear() {
  return 2016 - this.age;
}

var p = new person("A", 22);
document.write(p.yearOfBirth());

This code explains it.

A new object is created (new)

yearOfBirth is used because it returns a value

If you check the value, it's what it should be.

(Bad explaining)

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