【问题标题】:how to extend javascript classes如何扩展javascript类
【发布时间】:2010-09-18 19:28:23
【问题描述】:

为什么子类没有 echo() 方法?

Parent = function(){
    this.name = 'abc';
}

Parent.prototype.echo = function(){
    alert(this.name);
}

Child = function(){
    $.extend(this,  Parent);
}

var x = new Child();

x.echo();

如何在Javascript中继承父类?

【问题讨论】:

  • 这是使用 jQuery 吗? 'plain' javascript 中的子类化不能以这种方式工作。
  • 把 jQuery $.extend 扔进去只会把一切搞得一团糟。

标签: javascript class inheritance


【解决方案1】:

您需要将Child的原型设置为Parent。

function Parent() {
    this.name = 'abc';
}

Parent.prototype.echo = function () {
    alert(this.name);
}

function Child() {

}

Child.prototype = new Parent()

var x = new Child();

x.echo();

【讨论】:

    【解决方案2】:

    我假设您使用 jQuery。 jQuery 扩展系统使用对象,而不是“类”,请参阅:http://api.jquery.com/jQuery.extend/

    【讨论】:

      【解决方案3】:
      • javascript 中没有“类”,只有对象和原型继承
      • Parent、Child 不是类,它们是函数(以及对象)
      • 在 Child 中,“this”指的是全局对象(浏览器的“window”)
      • 使用Child.prototype = new Parent()

      【讨论】:

        猜你喜欢
        • 2013-02-18
        • 2020-07-22
        • 2013-04-27
        • 2017-03-25
        • 1970-01-01
        • 2011-01-16
        • 2017-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多