【问题标题】:Javascript inheritance with a priviledged function带有特权函数的 Javascript 继承
【发布时间】:2012-03-20 03:54:40
【问题描述】:

我正在简化我的示例以解决我的问题的核心。我有一个具有特权功能的基本 Javascript 类。我真的需要隐藏 myVar 不被看到,我也很想继承 baseClass。

function baseClass() {
  var myVar = new coolClass();

  this.myPrivileged = function() {
    myVar.coolFunction();
  }
}

我遇到的问题是我试图像这样继承:

function childClass() {

}
childClass.prototype = new baseClass();
childClass.prototype.reallyCoolFunction = function() {//Really cool stuff}

但只有一个 myVar 实例会被创建,并且不会工作,因为 coolClass 具有实例相关属性。 所以如果我这样做:

var x = new childClass();
var y = new childClass();

x 和 y 都将具有相同的 baseClass.myVar 实例

据我所知,我有两个选择:

  1. 使myPrivileged函数成为原型函数并暴露myVar
  2. 将baseClass 的内部结构复制并粘贴到childClass 中(这让我想作呕)

我不是 javascript 专家,所以我希望有人能提出一个好主意。

提前致谢

【问题讨论】:

  • 你应该看看coffeeScript
  • @Kyle:您至少应该为您的评论提出一些理由。大多数人不愿意开始使用一些编译成 JS 的语言,因此无法调试。
  • @JuanMendes “无法调试?”不,不是。这只是你的意见。
  • @Kyle 您的评论只是评论。 CoffeeScript 似乎很有用,但似乎根本没有解决我的问题。
  • @Kyle 除了使用console.log之外,你如何在 CoffeScript 中调试代码?

标签: javascript inheritance prototypal-inheritance


【解决方案1】:

首先,您不需要创建 baseClass 的实例来设置继承。您正在创建一个从未使用过的coolClass 实例。使用代理构造函数

function childClass() {
  ...
}

function surrogateCtor() {

}

surrogateCtor.prototype = baseClass;
childClass.prototype = new surogateCtor();

在你的childClass中,你需要调用父类的构造函数

function childClass() {
    baseClass.call(this);
}

这将确保每次实例化子类http://jsfiddle.net/mendesjuan/h2ypL/时都会初始化基类

查看我关于 JS 中继承的帖子http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 2018-03-31
    • 2013-08-21
    • 2012-11-17
    • 2017-08-03
    • 1970-01-01
    • 2013-10-02
    • 2014-02-25
    • 1970-01-01
    相关资源
    最近更新 更多