JavaScript中的instanceof运算符是什么?

本文翻译自:What is the instanceof operator in JavaScript?

The instanceof keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language. JavaScript中的instanceof关键字在第一次遇到时会非常混乱,因为人们倾向于认为JavaScript不是面向对象的编程语言。

  • What is it? 它是什么?
  • What problems does it solve? 它解决了什么问题?
  • When is it appropriate and when not? 什么时候适当,什么时候不适合?

#1楼

参考:https://stackoom.com/question/AHA6/JavaScript中的instanceof运算符是什么


#2楼

On the question "When is it appropriate and when not?", my 2 cents: 关于“什么时候适当,什么时候不适合?”的问题,我的2美分:

instanceof is rarely useful in production code, but useful in tests where you want to assert that your code returns / creates objects of the correct types. instanceof在生产代码中很少有用,但在要断言代码返回/创建正确类型的对象的测试中很有用。 By being explicit about the kinds of objects your code is returning / creating, your tests become more powerful as a tool for understanding and documenting your code. 通过明确您的代码返回/创建的对象类型,您的测试将变得更加强大,可以作为理解和记录代码的工具。


#3楼

I just found a real-world application and will use it more often now, I think. 我认为,我刚刚找到了一个真实世界的应用程序并且现在会更频繁地使用它。

If you use jQuery events, sometimes you want to write a more generic function which may also be called directly (without event). 如果你使用jQuery事件,有时你想编写一个更通用的函数,也可以直接调用(没有事件)。 You can use instanceof to check if the first parameter of your function is an instance of jQuery.Event and react appropriately. 您可以使用instanceof来检查函数的第一个参数是否是jQuery.Event的实例并做出适当的反应。

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

In my case, the function needed to calculate something either for all (via click event on a button) or only one specific element. 在我的例子中,函数需要为所有(通过按钮上的单击事件)或仅一个特定元素计算某些内容。 The code I used: 我用过的代码:

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

#4楼

instanceof 的instanceof

The Left Hand Side (LHS) operand is the actual object being tested to the Right Hand Side (RHS) operand which is the actual constructor of a class. 左侧(LHS)操作数是被测试到右侧(RHS)操作数的实际对象,该操作数是类的实际构造函数。 The basic definition is: 基本定义是:

Checks the current object and returns true if the object
is of the specified object type.

Here are some good examples and here is an example taken directly from Mozilla's developer site : 以下是一些很好的示例 ,这是一个直接从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)

One thing worth mentioning is instanceof evaluates to true if the object inherits from the classe's prototype: 值得一提的是,如果对象继承自classe的原型,则instanceof计算结果为true:

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

That is p instanceof Person is true since p inherits from Person.prototype . 这是p instanceof Person是真的,因为p继承自Person.prototype

Per the OP's request 根据OP的要求

I've added a small example with some sample code and an explanation. 我添加了一个带有一些示例代码和解释的小例子。

When you declare a variable you give it a specific type. 声明变量时,为其指定特定类型。

For instance: 例如:

int i;
float f;
Customer c;

The above show you some variables, namely i , f , and c . 以上显示了一些变量,即ifc The types are integer , float and a user defined Customer data type. 类型是integerfloat和用户定义的Customer数据类型。 Types such as the above could be for any language, not just JavaScript. 上述类型可以用于任何语言,而不仅仅是JavaScript。 However, with JavaScript when you declare a variable you don't explicitly define a type, var x , x could be a number / string / a user defined data type. 但是,使用JavaScript声明变量时未明确定义类型, var x ,x可以是数字/字符串/用户定义的数据类型。 So what instanceof does is it checks the object to see if it is of the type specified so from above taking the Customer object we could do: 那么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!

Above we've seen that c was declared with the type Customer . 上面我们已经看到c是用Customer类型声明的。 We've new'd it and checked whether it is of type Customer or not. 我们已经新了,并检查它是否属于Customer类型。 Sure is, it returns true. 当然,它返回true。 Then still using the Customer object we check if it is a String . 然后仍然使用Customer对象检查它是否是String Nope, definitely not a String we newed a Customer object not a String object. 不,绝对不是String我们新建了Customer对象而不是String对象。 In this case, it returns false. 在这种情况下,它返回false。

It really is that simple! 真的很简单!


#5楼

//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);

#6楼

instanceof is just syntactic sugar for isPrototypeOf : instanceof只是isPrototypeOf语法糖:

function Ctor() {}
var o = new Ctor();

o instanceof Ctor; // true
Ctor.prototype.isPrototypeOf(o); // true

o instanceof Ctor === Ctor.prototype.isPrototypeOf(o); // equivalent

instanceof just depends on the prototype of a constructor of an object. instanceof只取决于对象构造函数的原型。

A constructor is just a normal function. 构造函数只是一个普通的函数。 Strictly speaking it is a function object, since everything is an object in Javascript. 严格来说它是一个函数对象,因为一切都是Javascript中的对象。 And this function object has a prototype, because every function has a prototype. 而且这个函数对象有一个原型,因为每个函数都有一个原型。

A prototype is just a normal object, which is located within the prototype chain of another object. 原型只是一个普通对象,位于另一个对象的原型链中。 That means being in the prototype chain of another object makes an object to a prototype: 这意味着在另一个对象的原型链中创建一个原型的对象:

function f() {} //  ordinary function
var o = {}, // ordinary object
 p;

f.prototype = o; // oops, o is a prototype now
p = new f(); // oops, f is a constructor now

o.isPrototypeOf(p); // true
p instanceof f; // true

The instanceof operator should be avoided because it fakes classes, which do not exist in Javascript. 应该避免使用instanceof运算符,因为它伪造了Javascript中不存在的类。 Despite the class keyword not in ES2015 either, since class is again just syntactic sugar for...but that's another story. 尽管class关键字也不在ES2015中,因为class再次只是语法糖......但这是另一个故事。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值