Make all prototype functions inherit another prototype

Asked

Viewed 38 times

2

I’m starting my studies with javascript prototypes, as soon as I started, I came across a problem that I couldn’t solve. Follow the code

var ComponentAction = function(component){
 this.comp = component;
}

ComponentAction.prototype.remove = function(){}
ComponentAction.prototype.addContent = function(){}

var Component = function(){}

Component.prototype.submitButton = function(){
    return new ComponentAction(this);
}
Component.prototype.alertButton = function(){
    return new ComponentAction(this);
}



let sb = new Component();
sb.submitButton().addContent('...');

It is possible to make the function submitButton or any other function that is part of Component inherits all methods contained in Componentaction without needing to return a new Componentaction(this) in each of the functions of Component?

  • 2

    There is more than one way to do this, but is it the best option? Why not declare the methods directly in the prototype of Component?

  • But in this way I could access the addContent() method as in Sb.submitButton(). addContent('...'); ?

  • 1

    @Edgar to chain methods that way you just have to return the this (the instance of the object) at the end of each method. Take a look at this bfavaretto response: https://answall.com/a/56179/129

  • @Sergio, now that I saw the answer was very clear. Thank you both for your contributions!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.