在javascript中基类范围内评估子类方法 [英] Evaluate subclass method inside base class scope in javascript

查看:135
本文介绍了在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();

如何告诉呼叫 B()对基类进行评估? (即基类的调用c)这是不可能的。

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?

推荐答案

通常我会推荐 myFunc。 apply myFunc.eval ;这是我在javascript中解释为相对于基类。

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

然而,根据你的标题,你说内部基类范围;如果我正确地假设你正在谈论闭包,并且能够引用外部函数中的变量,这是不可能的,除了可能保持一个entrypoint到闭包中,你可以传递请求eval风格...但如果你这样,你可能还有一个对象,如 this._private.C

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.

如果你说你的动机为 this.C = function(){...} 并访问 this.C(),我可以给出一个更清楚的答案。 p>

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


这将允许C在实例上调用/基本上暴露它。没有理由暴露它,因为它应该是一个帮助方法我想你可以说我的主要沮丧是辅助方法不能被子类继承。--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();

这篇关于在javascript中基类范围内评估子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆