+ 1

I've no idea why this prints NaN. HEEELP!

function person(name, age, color) { this.name = name; this.age = age; this.skincolor = color; this.YearOfBirth = Born(); } function Born() { return 2019 - this.age; } var p1 = new person("Jane ", 42, "white"); document.write(p1.YearOfBirth);

15th Dec 2019, 8:54 AM
Eunjae Lee
Eunjae Lee - avatar
8 Antworten
+ 3
Try function person(name, age, color) { this.name = name; this.age = age; this.skincolor = color; this.born = function() { return 2019 - this.age; } this.YearOfBirth = this.born(); } var p1 = new person("Jane ", 42, "white"); document.write(p1.YearOfBirth);
15th Dec 2019, 9:21 AM
Calviղ
Calviղ - avatar
+ 2
Mystic Life Atleast it does not look like Java at all. Java would look like this: class Person { private String name; private int age; private String skincolor; private int YearOfBirth; Person(String name, int age, String color) { this.name = name; this.age = age; this.skincolor = color; this.YearOfBirth = this.Born(); } private int Born() { return 2019 - this.age; } } class MyClass { public static void main(String args[]) { Person p1 = new Person("Jane ", 42, "white"); System.out.println(p1.YearOfBirth); } }
15th Dec 2019, 9:38 AM
Seb TheS
Seb TheS - avatar
+ 2
Mystic Life this represents an object self. You can give this object variables: this.age = 400; The variables won't be confused with other object variables. You can have 2 or more objects with the same object variable name. Objects can also have functions.
15th Dec 2019, 9:43 AM
Seb TheS
Seb TheS - avatar
+ 1
How would function Born know what is "this"? Shortly the problem is in that you used this-keyword in Born-function. But I assume you can make a solution or 2 by yourself.
15th Dec 2019, 9:14 AM
Seb TheS
Seb TheS - avatar
+ 1
Mystic Life Could you explain why it does not look like JavaScript?
15th Dec 2019, 9:30 AM
Seb TheS
Seb TheS - avatar
+ 1
Seb TheS I understood your point. Thanks.
15th Dec 2019, 10:04 AM
Mystic Life
Mystic Life - avatar
0
Did you copy it from java? It doesn't seem like javascript. Because person function is like a java class constructor.
15th Dec 2019, 9:23 AM
Mystic Life
Mystic Life - avatar
0
What is the purpose using "this" in the person function?
15th Dec 2019, 9:36 AM
Mystic Life
Mystic Life - avatar