3

In the following code, why does instanceof return false for both Shape and Rectangle? Also why do the own properties of rec include both x and y from the superclass?

    function Shape(x, y) {
        this.x=x;
        this.y=y;
    }
    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 = Object.create(Shape.prototype);
    Rectangle.prototype.area = function() {
        return this.w * this.h;
    };
    var rec = new Rectangle(0,0,10,10);
    console.log("instanceof = " + rec instanceof Shape);
    console.log("instanceof = " + rec instanceof Rectangle);
    rec.move(2,3);
    console.log("area = " + rec.area());
    console.log(Object.getOwnPropertyNames(rec));
2
  • you should set the prototype for Rectangle to new Shape(). You should check out codeacademy.com if you're new to JavaScript. Commented Nov 10, 2012 at 23:01
  • @GlennFerrieLive: Object.create(Shape.prototype) is preferred because it doesn't require an invocation of the Shape constructor, and gives you an empty object. Commented Nov 10, 2012 at 23:35

1 Answer 1

9

Because + is evaluated before instanceof. So you're asking if:

"instanceof = " + rec

...a String, is an instanceof your constructors, which it won't be.

Either add parenthesis to force the order:

console.log("instanceof = " + (rec instanceof Shape));

Or, since console.log accepts any number of arguments, pass it as its own:

console.log("instanceof = ", rec instanceof Shape);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.