+ 1

Help me.JS object constructor

Why output is "function(){ return "Name : "+this.first+" "+this.second; } " instead of Sachin M? code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>js obj</title> <link rel="stylesheet" href="style.css"> </head> <body> <script> function person(first,second,age,hobby){ this.firstName=first; this.secondName=second; this.age=age; this.hobby=hobby; this.name=function(){ return "Name : "+this.first+" "+this.second; } } var p1=new person("Sachin","M",18,"Football"); document.write(p1.name); </script> </body> </html> link to code play ground:https://code.sololearn.com/W1NOdBg3508Q/#html

21st Sep 2018, 1:35 PM
Sachin M
Sachin M - avatar
2 Respostas
+ 6
//2 errors corrected function person(first,second,age,hobby){ this.first=first; this.second=second; this.age=age; this.hobby=hobby; this.name=function(){ return "Name : "+this.first+" "+this.second; } } var p1=new person("Sachin","M",18,"Football"); document.write(p1.name());
21st Sep 2018, 1:44 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
When you use "p1.name" you get/set the code of the function, to execute it you have to use "p1.name()"
21st Sep 2018, 1:45 PM
Valen.H. ~
Valen.H. ~ - avatar