You did not create an instance of person
, and you did not call a property of that instance:
bornYear
references this
, which seems intended to be a person
instance, so you must bind this
to it somehow.
- As you defined a property
yearOfBirth
, it would be appropriate to call that method.
Also, your bornYear
function is limited to the year 2020. You should take the current year, using the Date
constructor.
Here is how it could work:
function person(name, age){
this.name = name;
this.age = age;
this.yearOfBirth = bornYear.bind(this); // bind this
}
function bornYear(){
// Use the current year to calculate year of birth
return new Date().getFullYear() - this.age;
}
// First create an instance, then call the method
document.write(new person("Helen", 18).yearOfBirth());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…