+ 2
question - object - adding method
function person(name, age) { this.name = name; this.age = age; this.changeName = function (name) { this.name = name; } } var p = new person("David", 21); p.changeName("John"); document.write(p);// i changed p.name to p i want output [john 21] help me please
2 Answers
+ 1
document.write(p.name + " " + p.age);
0
function person(name, age) {
this.name = name;
this.age = age;
this.changeName = function (name) {
this.name = name;
}
this.format = function (){
return "[" + this.name + " " + this.age + "]" ;
}
}
var p = new person("David", 21);
p.changeName("John");
document.write(p.format());
document.write(JSON.stringify(p));
you can use something like above your own format function, or you can also go for JSON.stringify() which will format object data accordingly.