0
Why does this not work
function person(name, age) { this.name = name; this.age = age; this.changeName = function (name) { this.name = name; } this.BirthYear = function(age) { return 2020 - this.age; } } var p2 = new person("Jones",69); document.write(p2.name+", "+p2.BirthYear); The result is: "Jones, undefined"
4 odpowiedzi
+ 2
As the others have said, this.BirthYear is a function. In order to get it to run, you need to stick a pair of parthenses after it (this.BirthYear()). Without those, you'd actually normally be simply writing out the "contents" of the function this.BirthYear, not its output.
Also, a few comments. Normally, classes and class-like constructor functions in most languages should be PascalCase (that is, all words including the first word have their first letter capitalized). This is a sort of short cut for "this is a class". Anything else, including function/variable names, should be camelCase (all words EXCEPT the first word have their first letter capitalized; first word is all lower-case).
In addition, if you're defining a constructor function, it's often best not to define functions as properties of the "this" object as you have; but instead to define them as part of the object prototype.
So I'd rewrite this as:
function Person(name, age) {
//capitalize Person
this.name = name;
this.age = age;
//move functions outside the constructor
}
Person.prototype.changeName = function (name) {
this.name = name;
}
Person.prototype.birthYear = function (age) {
//change BirthYear to birthYear
return 2020 - this.age;
}
+ 1
hi, it's probably because this.BirthYear is define like a function with no property name inside (look the changeName function)
0
I found why but I don't know why it works. I forgot to ad() behind p2.Birthyear document.write(p2.name+", "+p2.BirthYear())
0
p2.BirthYear() is function calling. Function only return returned value...
p2.BirthYear is calling a variable...
And youre assigning a function reference to BirthYear ..