为什么object和constructor.prototype在JavaScript中设置为Base?

时间:2012-11-11 07:10:32

标签: javascript

这是我的小程序。当我在调试模式中检查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;
    }

1 个答案:

答案 0 :(得分:0)

看看Why [not] to use the new keyword here?。您可能不会使用它并创建它的新实例,而只是从Base.prototype继承。

  

constructor.prototype也是Base。为什么不塑造?

我不确定你在这里指的是constructor

  • 所有对象的constructor属性为Base,因为所有对象都从Base.prototype对象继承此原型。设置继承链后,您没有覆盖它。这不是必要的,而是好的风格:Shape.prototype.constructor = ShapeRectangle.prototype.constructor = Rectangle - 这些原型对象是从Base继承的被覆盖的对象。

  • constructor功能的instanceOf参数。您传递Rectangleconstructor.prototypeRectangle的原型对象,Base继承但不同。

  

当我在调试模式中检查rec的值时,对象是Base {x = 0,y = 0,w = 10,more ...}

通常不是。 Base是特别的,例如主持人对象?您的rec对象是Base的实例,因此可能会以不同的方式显示。

rec只是一个继承自Rectangle.prototype的{​​{1}}继承自Shape.prototype的继承自Base.prototype的对象。假设Base是函数您定义的是Object.prototype继承自null