为什么instanceof在JavaScript中返回false?

J A*_*Any 3 javascript

在下面的代码中,为什么instanceof对Shape和Rectangle都返回false?为什么rec的属性包括超类中的x和y?

    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));
Run Code Online (Sandbox Code Playgroud)

Jon*_*ski 9

因为+以前是评估过的instanceof.所以你问是否:

"instanceof = " + rec
Run Code Online (Sandbox Code Playgroud)

...... a String,是instanceof你的构造者,它不会是.

添加括号以强制执行订单:

console.log("instanceof = " + (rec instanceof Shape));
Run Code Online (Sandbox Code Playgroud)

或者,因为console.log接受任意数量的参数,将其作为自己的参数传递:

console.log("instanceof = ", rec instanceof Shape);
Run Code Online (Sandbox Code Playgroud)