日期:2014-05-16  浏览次数:20508 次

JavaScript中instanceof对于不同的构造器可能都返回true

我们知道 instanceof 运算符用来检查对象是否为某构造器的实例。下面列举它返回true的各种情景。

?

1、对象obj是通过new Constructor创建的,那么?obj instanceof Constructor?为true

function Person(n, a) {
    this.name = n;
    this.age = a;
}
var p = new Person('John Backus', 82);
console.log(p instanceof Person); // true

?

2、如果存在继承关系,那么?子类实例 instanceof 父类?也会返回true

function A(){}
function B(){}
B.prototype = new A(); // B继承于A
 
var b = new B();
console.log(b instanceof A); // true

?

?3、由于Object是根类,所有其它自定义类都继承于它,因此?任意构造器的实例 instanceof Object?都返回true

?

function A() {}
var a = new A();
console.log(a instanceof Object); // true
 
var str = new String('hello');
console.log(str instanceof Object); // true
 
var num = new Number(1);
console.log(num instanceof Object); // true

?

甚至包括构造器自身

function A() {}
console.log(A instanceof Object); // true
console.log(String instanceof Object); // true
console.log(Number instanceof Object); // true

?

4、所有构造器 instanceof Function?返回true

?

function A() {}
console.log(A instanceof Function); // true
console.log(String instanceof Function); // true
console.log(Number instanceof Function); // true
?

?

以上四点总结为一句话:如果某实例是通过某类或其子类的创建的,那么instanceof就返回true。或者说某构造函数的原型 存在与对象obj的内部原型链上,那么返回true。即instanceof的结果与构造器自身并无直接关系。这在许多语言中都是通用的。

?

Java中定义了一个类Person,实例p对于Person和Object都返回true

class Person {
    public String name;
    public int age;
    Person (String n, int a) {
        this.name = name;
        this.age = a;
    }
    public static void main(String[] args) {
        Person p = new Person("John Backus", 82);
        System.out.println(p instanceof Person); // true
        System.out.println(p instanceof Object); // true
    }
}

?

Java中如果存在继承关系,那么?子类实例 instanceof 父类?也返回true

// 父类
class Person {
    public String name;
    public int age;
    Person (String n, int a) {
        name = name;
        age = a;
    }
}
// 子类
public class Man extends Person{
    public String university;
    Man(String n, int a, String s) {
        super(n, a);
        university = s;
    }
    public static void main(String[] args) {
        Man mm = new Man("John Resig", 29, "PKU");
        System.out.println(mm instanceof Man); // true
        System.out.println(mm instanceof Person); // 也是true
    }
}
<