开发者

Evaluate subclass method inside base class scope in javascript

开发者 https://www.devze.com 2023-03-15 02:42 出处:网络
base = function () { this.A = function () { this.B(); } var C = function () { alert(\'I am C\'); } } sub = function () {
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? (i.e. 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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号