简体   繁体   中英

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.prototype = new base();

(new sub()).A();

How can I tell the call to B() to evaluate with respect to the base class? (ie call c of the base class) Is this impossible?

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 = new base();

(new sub()).A();

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM