【问题标题】:Javascript class inheritenceJavascript类继承
【发布时间】:2011-11-27 19:45:38
【问题描述】:

我正在尝试学习如何在 javascript 中使用“类”。

这是我的代码:

function Shape(x, y) {
    this.x= x;
    this.y= y;    
}

Shape.prototype.toString= function() {
        return 'Shape at '+this.x+', '+this.y;
    };

function Circle(x, y, r) {
    Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
    this.r= r;
}
Circle.prototype= $.extend(true, {}, Shape.prototype);

Circle.prototype.toString= function() {
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}

var c = new Circle(1,2,3);
alert(c);

有没有办法在它的构造函数中定义 Shape 的 toString 函数,或者在这种情况下没有意义?

【问题讨论】:

  • this.toString = function() { ... } 在这种情况下不起作用吗?
  • 不,不是。查看区别:jsfiddle.net/paptamas/qDSkjjsfiddle.net/paptamas/cbnLB
  • 原型是正确的方法。它将创建一次 toString 函数。在构造函数中,它会随着每个新的创建。
  • John Resig 对类继承有一些非常深刻的看法,还有一个很棒的小脚本可以解决 js 中的许多继承问题:ejohn.org/blog/simple-javascript-inheritance
  • 以这种方式扩展需要注意的一点:new Shape().constructor === Shape,但new Circle().constructor !== Circle

标签: javascript jquery inheritance


【解决方案1】:

根据我的理解:

  1. 当您将 .toString() 移动到构造函数中 时,.toString() 将成为实例的显式成员。因此,任何对 .toString() 的调用都会触发该显式成员。

示例:http://jsfiddle.net/paptamas/qDSkj/

  1. 但是,当您将其定义为原型时(在没有称为 .toString() 的显式成员的情况下),对 .toString() 方法的任何调用都会触发为调用类型定义的 .toString() 函数对象(在您的情况下为圆圈)。

示例:http://jsfiddle.net/paptamas/cbnLB/

换句话说,显式成员优先于原型定义和当你说的时候

this.toString = function() ...

您将该函数定义为您的实例的成员(与您的类型的成员相反 - 这在某种程度上也没有优化)。

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2013-05-10
    相关资源
    最近更新 更多