0

in the following code, i need call the "private" method run in the sub class Worker

function Person(scope, ...) {
  scope.name = "Juan";

  var run = function() {
     console.log(scope.name + " is running");
  };
}

function Worker(scope, ...) {
  Person.call(this, scope, ...);

  var jumpAndRun = function() {
     console.log(scope.name + " is jumping");
     run(); // how to call this
  };
}

Worker.prototype = Object.create(People.prototype);

currently if i call run method i get an Error: run is not defined!

6
  • That's outright impossible. It's totally private to the People constructor function scope, not somehow "protected". Commented Sep 9, 2014 at 15:05
  • Why can't you make it public? From where are run and jumpAndRun invoked anyway? Commented Sep 9, 2014 at 15:06
  • My recommendation: Don't try to simulate something that the language does not support. Keep it simple. It makes the code: easier to understand and easier to maintain. Commented Sep 9, 2014 at 15:07
  • @FelixKling yeah you are right but i wont rewrite many code is the same in many places, currently i'm refactoring Commented Sep 9, 2014 at 15:16
  • Also, what the heck is scope? Commented Sep 9, 2014 at 15:22

1 Answer 1

3

Sorry, can't do it, unless the People class (which should be called Person) makes that method available.

A common practice is to make "private" methods start with an underscore. It does not 100% grant any security, but it at least gives other developers a hint that it is meant to be private.

function Person(scope, ...) {
  scope.name = "Juan";

  var run = function() {
     console.log(scope.name + " is running");
  };

  this._run = run;
}

function Worker(scope, ...) {
  Person.call(this, scope, ...);

  var jumpAndRun = function() {
     console.log(scope.name + " is jumping");
     this._run(); // how to call this
  };
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your jumpAndRun function would need to be a method as well, though.
@rkmax have you added the this._run = run; in the Person costructor?
Here I've done what I think is right, here is a fiddle: jsfiddle.net/zLqb1tyo

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.