+ 2
Js Prototype Q
When I use the code: function ex(){ this.x, this.y;....... } It behaves the same as this code: function ex(x,y){ this.x, this.y;....... } Is there any advantage to adding or not adding to the function? Or is it just preference.
2 ответов
+ 2
Hi Ole 113
your first example won't work if you want to initialize properties on instantiation.
Try this
function monster(name,life){
this.name=name;
this.life=life;
}
function emptymonster(){
this.name=name;
this.life=life;
}
let monster1=new monster("slime",10);
let emonster=new emptymonster("goul",6)
console.log (monster1.name)
//slime
console.log (emonster.name)
//reference error,life is not defined
+ 3
And just to finish off Prototype inheritance, you can add a method like this
function monster(name,life){
this.name=name;
this.life=life;
}
let monster1=new monster("slime",10);
console.log (monster1.name)
//slime
monster.prototype.status = function() {
return `monster ${this.name} has life ${this.life}`
};
console.log(monster1.status());
// monster slime has life 10