第一次遇到JavaScript中的instanceof关键字时,可能会让人非常困惑,因为人们倾向于认为JavaScript不是面向对象的编程语言。

是什么? 它能解决什么问题? 什么时候合适,什么时候不合适?


当前回答

我刚刚发现了一个真实的应用程序,我想现在会更经常地使用它。

如果你使用jQuery事件,有时你想写一个更通用的函数,也可以直接调用(没有事件)。您可以使用instanceof来检查函数的第一个参数是否是jQuery实例。事件并做出适当的反应。

var myFunction = function (el) {                
    if (el instanceof $.Event) 
        // event specific code
    else
        // generic code
};

$('button').click(recalc);    // Will execute event specific code
recalc('myParameter');  // Will execute generic code

在我的例子中,函数需要为所有(通过按钮上的单击事件)或仅为一个特定元素计算一些东西。我使用的代码:

var recalc = function (el) { 
    el = (el == undefined || el instanceof $.Event) ? $('span.allItems') : $(el);
    // calculate...
};

其他回答

运算符

左手边(LHS)操作数是被测试到右手边(RHS)操作数的实际对象,右手边(RHS)操作数是类的实际构造函数。基本定义是:

检查当前对象,如果对象是指定的对象类型,则返回true。

这里有一些很好的例子,这里有一个直接取自Mozilla开发者网站的例子:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)

值得一提的是,如果对象继承了类的原型,instanceof的值为true:

var p = new Person("Jon");
p instanceof Person

即p instanceof Person为真,因为p继承自Person.prototype。

根据指挥官的要求

I've added a small example with some sample code and an explanation.

当你声明一个变量时,你给它一个特定的类型。

例如:

int i;
float f;
Customer c;

上面显示了一些变量,即i, f和c。类型是整数,浮点数和用户定义的客户数据类型。像上面这样的类型可以适用于任何语言,而不仅仅是JavaScript。然而,在JavaScript中,当你声明一个变量时,你不会显式地定义一个类型,var x, x可以是一个数字/字符串/用户定义的数据类型。instanceof所做的是检查对象是否为指定的类型,因此从上面获取Customer对象,我们可以这样做:

var c = new Customer();
c instanceof Customer; //Returns true as c is just a customer
c instanceof String; //Returns false as c is not a string, it's a customer silly!

上面我们已经看到c是用Customer类型声明的。我们已经更新了,并检查了是否为客户类型。当然,它返回true。然后仍然使用Customer对象检查它是否是String对象。不,肯定不是String我们新建了Customer对象,不是String对象。在这种情况下,它返回false。

真的就是这么简单!

你可以用它来进行错误处理和调试,就像这样:

try{
    somefunction();
} 
catch(error){
    if (error instanceof TypeError) {
        // Handle type Error
    } else if (error instanceof ReferenceError) {
        // Handle ReferenceError
    } else {
        // Handle all other error types
    }
}

到目前为止,instanceof有一个重要的方面似乎没有在任何注释中提到:继承。由于原型继承,使用instanceof计算的变量对于多个“类型”可能返回true。

例如,让我们定义一个类型和一个子类型:

function Foo(){ //a Foo constructor
    //assign some props
    return this;
}

function SubFoo(){ //a SubFoo constructor
    Foo.call( this ); //inherit static props
    //assign some new props
    return this;
}

SubFoo.prototype = Object.create(Foo.prototype); // Inherit prototype
SubFoo.prototype.constructor = SubFoo;

现在我们有了几个“类”,让我们创建一些实例,并找出它们是什么实例:

var 
    foo = new Foo()
,   subfoo = new SubFoo()
;

alert( 
    "Q: Is foo an instance of Foo? "
+   "A: " + ( foo instanceof Foo ) 
); // -> true

alert( 
    "Q: Is foo an instance of SubFoo? " 
+   "A: " + ( foo instanceof SubFoo ) 
); // -> false

alert( 
    "Q: Is subfoo an instance of Foo? "
+   "A: " + ( subfoo instanceof Foo ) 
); // -> true

alert( 
    "Q: Is subfoo an instance of SubFoo? "
+   "A: " + ( subfoo instanceof SubFoo ) 
); // -> true

alert( 
    "Q: Is subfoo an instance of Object? "
+   "A: " + ( subfoo instanceof Object ) 
); // -> true

看到最后一行了吗?所有对函数的“new”调用都会返回一个继承自object的对象。即使在使用对象创建简写时也是如此:

alert( 
    "Q: Is {} an instance of Object? "
+   "A: " + ( {} instanceof Object ) 
); // -> true

那么“类”定义本身呢?它们是什么实例?

alert( 
    "Q: Is Foo an instance of Object? "
+   "A:" + ( Foo instanceof Object) 
); // -> true

alert( 
    "Q: Is Foo an instance of Function? "
+   "A:" + ( Foo instanceof Function) 
); // -> true

我觉得理解任何对象都可以是MULTIPLE类型的实例是很重要的,因为你可能(错误地)假设你可以通过使用instanceof来区分对象和函数。最后一个例子清楚地显示了函数是一个对象。

如果您正在使用任何继承模式,并希望通过鸭子类型以外的方法确认对象的后代,这也很重要。

//Vehicle is a function. But by naming conventions
//(first letter is uppercase), it is also an object
//constructor function ("class").
function Vehicle(numWheels) {
    this.numWheels = numWheels;
}

//We can create new instances and check their types.
myRoadster = new Vehicle(4);
alert(myRoadster instanceof Vehicle);

我刚刚发现了一个真实的应用程序,我想现在会更经常地使用它。

如果你使用jQuery事件,有时你想写一个更通用的函数,也可以直接调用(没有事件)。您可以使用instanceof来检查函数的第一个参数是否是jQuery实例。事件并做出适当的反应。

var myFunction = function (el) {                
    if (el instanceof $.Event) 
        // event specific code
    else
        // generic code
};

$('button').click(recalc);    // Will execute event specific code
recalc('myParameter');  // Will execute generic code

在我的例子中,函数需要为所有(通过按钮上的单击事件)或仅为一个特定元素计算一些东西。我使用的代码:

var recalc = function (el) { 
    el = (el == undefined || el instanceof $.Event) ? $('span.allItems') : $(el);
    // calculate...
};