+ 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);
8 Réponses
+ 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);
+ 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);
}
}
+ 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.
+ 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.
+ 1
Mystic Life Could you explain why it does not look like JavaScript?
+ 1
Seb TheS I understood your point. Thanks.
0
Did you copy it from java? It doesn't seem like javascript. Because person function is like a java class constructor.
0
What is the purpose using "this" in the person function?