0

I've searched on SO and elsewhere for a simple example of inheritance and can't find one. Examples I've seen are obscure, complex, or just make me uncomfortable. I have several service functions that all share some functionality, from what I would call a baseservice:

function baseservice() {
   var loadAnimate = function () {
      $('#ajax-spinner').show();
    };
   var loadComplete = function () {
      $('#ajax-spinner').hide();
    };
   var apiEndpoint = function() {
      return "http://api.com/api/";
    };
};

I have other services now that have this functionality:

var documentservice = function() {
    // repeated code
    var loadAnimate = function () {
        $('#ajax-spinner').show();
    };
    var loadComplete = function () {
        $('#ajax-spinner').hide();
    };

    var apiEndpoint = "http://api.com/api/";

    var sendRequest = function (payload, callback) {
        loadAnimate();
        // do stuff with apiEndpoint
        // call loadComplete on promise
    };

How can I provide documentservice with access to those items in baseservice?

3

1 Answer 1

2

Since Javascript is a prototypical language, it doesn't have the same sort of class inheritance that a language like, say, Java has. If you want a very simple instance of inheritance, you could try something like:

function baseservice() {
  this.loadAnimate = function () {
    $('#ajax-spinner').show();
  };
  this.loadComplete = function () {
    $('#ajax-spinner').hide();
  };
  this.apiEndpoint = function() {
    return "http://api.com/api/";
  };
};

var documentservice = new baseservice();
documentservice.sendRequest() = function() { /* ... */ }

Then, documentservice has all of baseservice's members (note the this. in baseservice's function declaration instead of var).

If you don't want to have to use the new keyword, you can create a function extend either adds a field pointing to baseservice (document.baseservice = baseservice) or does a deep (recursive) copy, then adds documentservice.sendRequest.

Of course, folks have already worked on this with things like ded/klass.

Sign up to request clarification or add additional context in comments.

1 Comment

JS works very differently to classical inheritance languages. Strongly advice that the OP read Crockford's "JavaScript the Good Parts" book. amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.