0

これが私の小さなプログラムです。デバッグモードで rec の値を確認すると、オブジェクトは Base { x=0, y=0, w=10, more...} です。それは長方形であるべきですか?また、constructor.prototype は Base です。なぜシェイプしないのですか?

    function Base() {
    }

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

    Shape.prototype = new Base();
    Shape.prototype.move = function(x, y) {
        this.x += x;
        this.y += y;
        console.log("x = " + this.x + " y = " + this.y);
    };

    function Rectangle(x, y, w, h) {
        Shape.call(this, x, y);
        this.w = w;
        this.h = h;
    }

    Rectangle.prototype = new Shape();
    Rectangle.prototype.area = function() {
        return this.w * this.h;
    };
    var rec = new Rectangle(0, 0, 10, 10);
    console.log(instanceOf(rec, Rectangle));

    function instanceOf(object, constructor) { 
        while (object != null) {
            if (object == constructor.prototype)
                return true;
            if ( typeof object == 'xml') {
                return constructor.prototype == XML.prototype;
            }
            object = object.__proto__;
        }
        return false;
    }
4

1 に答える 1

0

ここでキーワードを使用しない理由newをご覧ください。. それを使用して新しいインスタンスを作成するのではなく、 から継承するだけBase.prototypeです。

また、constructor.prototype は Base です。なぜシェイプしないのですか?

constructorあなたがここで何を指しているのかわかりません:

  • すべてのオブジェクトがこのプロトタイプをオブジェクトから継承するため、すべてのオブジェクトのconstructorプロパティはです。継承チェーンを設定した後に上書きしませんでした。実際には必要ありませんが、良いスタイルです: and - これらのプロトタイプ オブジェクトは、 から継承された上書きされたオブジェクトです。BaseBase.prototypeShape.prototype.constructor = ShapeRectangle.prototype.constructor = RectangleBase

  • 関数のconstructorパラメーターinstanceOfRectangleそこに渡すconstructor.prototypeと、 のプロトタイプ オブジェクトが渡されます。これはから継承Rectangleされますが、異なります。Base

デバッグモードで rec の値を確認すると、オブジェクトは Base { x=0, y=0, w=10, more...} です。

通常はありません。Baseホストオブジェクトなど、特別なものはありますか? オブジェクトrecは のインスタンスでBaseあるため、そのために表示が異なる場合があります。

recは単なるオブジェクトであり、継承元、Rectangle.prototype継承元、Shape.prototype継承元、継承元、…を定義した関数、Base.prototype継承元、継承元と仮定します。BaseObject.prototypenull

于 2012-11-11T12:05:15.060 に答える