Reputation: 210
this is my class
function User(){
this.nickname='nickname';
}
User.prototype.save=function(){
dosomething();
};
User.prototype.add=function(){
dosometing();
call save();
};
i want to call the save() function in the add() function,but i don't know how to do.I tried
User.prototype.add=function(){
save();
};
and User.prototype.add=function(){ User.prototype.save(); };
but both are wrong,and what should i do?
Upvotes: 1
Views: 94
Reputation: 17757
Ok.There are a few mistakes in your code.
Here we are using the classical model of inheritance.
Step 1.Create a constructor function. eg. function user(){...}
Step 2.Extend your prototype by adding methods.eg add,save etc
step 3.Create an instance to call methods.eg.MyInstance
function User(){
this.nickname='nickname';
}
User.prototype.dosomething=function(){
//some code
};
User.prototype.save=function(){
this.dosomething();
};
User.prototype.add=function(){
this.dosometing();
this.save();
};
Now lets say I want to call a method add.This is how its done.
var MyInstance = new User();//create an instance.
MyInstance.add();//call the function.
Outside the scope of your question : The same thing could be done by Prototypal Inheritance as well.
var UserPrototype={
save:function(){..},
add:function(){
this.save();
}
}
var MyInstance = Object.Create(UserPrototype);
MyInstance.add();
Upvotes: 3
Reputation: 9486
function User() {
this.nickname = 'nickname';
}
// ...
User.prototype.add = function() {
this.save();
};
You were not defining your User constructor properly.
Also, instances of User (created like var myUser = new User();
) can access their prototype's methods via this.methodNameHere();
Upvotes: 4