Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnologia Web para desenvolvedores
  2. JavaScript
  3. Referência JavaScript
  4. Operadores
  5. instanceof

Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.

View in EnglishAlways switch to English

instanceof

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨julho de 2015⁩.

O operadorinstanceof testa se um objeto tem, em seu prototype, a função construtora.

Experimente

function Car(make, model, year) {  this.make = make;  this.model = model;  this.year = year;}const auto = new Car("Honda", "Accord", 1998);console.log(auto instanceof Car);// Expected output: trueconsole.log(auto instanceof Object);// Expected output: true

Sintaxe

objeto instanceof construtor

Parâmetros

objeto

O objeto a ser testado

construtor

Função construtora a ser verificada

Descrição

O operador instanceof testa a presença da função construtora no prototype do objeto.

js
// definindo construtoresfunction C() {}function D() {}var o = new C();// true, porque: Object.getPrototypeOf(o) === C.prototypeo instanceof C;// false, porque D.prototype não está no prototype desse objetoo instanceof D;o instanceof Object; // true, porque:C.prototype instanceof Object; // trueC.prototype = {};var o2 = new C();o2 instanceof C; // true// false, porque C.prototype não está mais no prototype desse objetoo instanceof C;D.prototype = new C(); // use inheritancevar o3 = new D();o3 instanceof D; // trueo3 instanceof C; // true

Note que o resultado do instanceof pode alterar quando a gente altera o prototype da função construtora. No entanto, a gente não pode alterar (por padrão) o prototype do objeto. Só é possível fazer essa alteração usando a pseudopropriedade __proto__.

instanceof and multiple context (e.g. frames or windows)

Different scope have different execution environments. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance,[] instanceof window.frames[0].Array will returnfalse, becauseArray.prototype !== window.frames[0].Array and arrays inherit from the former. This may not make sense at first but when you start dealing with multiple frames or windows in your script and pass objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is in fact an Array usingArray.isArray(myObj)

Nota:Note for Mozilla developers:In code using XPCOMinstanceof has special effect:obj instanceof xpcomInterface (e.g.Components.interfaces.nsIFile) callsobj.QueryInterface(xpcomInterface) and returnstrue if QueryInterface succeeded. A side effect of such call is that you can usexpcomInterface's properties onobj after a successfulinstanceof test. Unlike standard JavaScript globals, the testobj instanceof xpcomInterfaceworks as expected even ifobj is from a different scope.

Examples

Demonstrating thatString andDate are of typeObject and exceptional cases

The following code usesinstanceof to demonstrate thatString andDate objects are also of typeObject (they are derived fromObject).

However, objects created with the object literal notation are an exception here: Although the prototype is undefined,instanceof Object returnstrue.

js
var simpleStr = "This is a simple string";var myString = new String();var newStr = new String("String created with constructor");var myDate = new Date();var myObj = {};simpleStr instanceof String; // returns false, checks the prototype chain, finds undefinedmyString instanceof String; // returns truenewStr instanceof String; // returns truemyString instanceof Object; // returns truemyObj instanceof Object; // returns true, despite an undefined prototype({}) instanceof Object; // returns true, same case as abovemyString instanceof Date; // returns falsemyDate instanceof Date; // returns truemyDate instanceof Object; // returns truemyDate instanceof String; // returns false

Demonstrating thatmycar is of typeCar and typeObject

The following code creates an object typeCar and an instance of that object type,mycar. Theinstanceof operator demonstrates that themycar object is of typeCar and of typeObject.

js
function Car(make, model, year) {  this.make = make;  this.model = model;  this.year = year;}var mycar = new Car("Honda", "Accord", 1998);var a = mycar instanceof Car; // retorna truevar b = mycar instanceof Object; // retorna true

Especificações

Specification
ECMAScript® 2026 Language Specification
# sec-relational-operators

Compatibilidade com navegadores

Veja também

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp