简体   繁体   English

在javascript中的基类范围内评估子类方法

[英]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? 我该如何告诉对B()的调用以针对基类进行评估? (ie call c of the base class) Is this impossible? (即调用基类的c)这是不可能的吗?

Normally I would recommend myFunc.apply and myFunc.eval ; 通常我会推荐myFunc.applymyFunc.eval ; that's what I interpret as "with respect to the base class" in javascript. 这就是我在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 . 如果我正确地假设您正在谈论闭包并且能够在外部函数中引用变量,那么这是不可能的,除非可能是在闭包中保留一个入口点,然后您可以将请求传递给eval样式...但是如果这样做,您可能还拥有一个类似于this._private.C的对象。

If you are attempting to keep things "private", it is not really worth bothering to do so in javascript. 如果您尝试将内容保持为“私有”,那么在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. 如果您说出您对this.C = function(){...}的动机,并以此this.C()访问,我也许可以给出一个更清晰的答案。

" 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 这将允许C在实例上被调用/本质上将其公开。没有理由公开它,因为它应该是一个辅助方法。我想您可能会说,我的主要沮丧之处是该辅助方法不能被继承。子类。

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 . Cbase内具有词法范围,因此仅当被同一范围内定义的其他方法调用时才可见。 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 . C只有在它的声明是其词法范围之外访问this.C ,而不是var C

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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