Skip to content Skip to sidebar Skip to footer

Evaluate Subclass Method Inside Base Class Scope In Javascript

base = function () { this.A = function () { this.B(); } var C = function () { alert('I am C'); } } sub = function () { this.B = function () { C(); } } sub

Solution 1:

Normally I would recommend myFunc.apply and myFunc.eval; that's what I interpret as "with respect to the base class" in javascript.

However based on your title, you say "inside base class scope"; if I assume correctly that you are talking about closures and being able to refer to variables in outer functions, this is impossible, except perhaps with keeping an entrypoint into the closure into which you can pass in requests eval-style... but if you do that, you might as well have a an object like this._private.C.

If you are attempting to keep things "private", it is not really worth bothering to do so in javascript.

If you say your motivation for this.C = function(){...} and access it as this.C(), I may be able to give a clearer answer.

"That would allow C to be called on instances / essentially expose it. There's no reason for it to be exposed since it's supposed to be a helper method. I guess you could say my main frustration is that helper methods can't be inherited by subclasses." --OP

In that case, it really isn't private. However what you can do is define your helper method where it belongs: appropriately in an outer scope. =) For example:

(function(){

  var C = function () {
    alert('I am C');
  }

  base = function () {
    this.A = function () {
      this.B();
    }
  }

  sub = function () {
    this.B = function () {
      C();
    }
  }

})();

sub.prototype = newbase();

(newsub()).A();

Solution 2:

You can't, at least not without changing the base class.

C has lexical scope within base, so is only visible when called by other methods defined within the same scope. It's currently a truly private method.

C can only be accessed outside of its lexical scope if it's declared as this.C instead of var C.

See http://jsfiddle.net/alnitak/DaSEN/

Post a Comment for "Evaluate Subclass Method Inside Base Class Scope In Javascript"