instanceOf . .
. (polymorphic) .
instanceof
:
obj instanceof Class
obj Class true .
:
class Rabbit {}
let rabbit = new Rabbit();
// Rabbit
alert( rabbit instanceof Rabbit ); // true
:
//
function Rabbit() {}
alert( new Rabbit() instanceof Rabbit ); // true
Array:
let arr = [1, 2, 3];
alert( arr instanceof Array ); // true
alert( arr instanceof Object ); // true
arr Object . Array Object .
instanceof . Symbol.hasInstance .
obj instanceof Class :
-
Symbol.hasInstance:Class[Symbol.hasInstance](obj).truefalse.instanceof.:
// instanceof // (animal) canEat class Animal { static [Symbol.hasInstance](obj) { if (obj.canEat) return true; } } let obj = { canEat: true }; alert(obj instanceof Animal); // true : Animal[Symbol.hasInstance](obj) -
Symbol.instanceof. :obj instanceOf ClassClass.prototypeobj.:
obj.__proto__ === Class.prototype? obj.__proto__.__proto__ === Class.prototype? obj.__proto__.__proto__.__proto__ === Class.prototype? ... // true true // falserabbit.__proto__ === Rabbit.prototype.:
class Animal {} class Rabbit extends Animal {} let rabbit = new Rabbit(); alert(rabbit instanceof Animal); // true // rabbit.__proto__ === Animal.prototype ( ) // rabbit.__proto__.__proto__ === Animal.prototype (! )
rabbit instanceof Animal Animal.prototype :
objA.isPrototypeOf(objB) objA objB true . obj instanceof Class Class.prototype.isPrototypeOf(obj) .
Class ! Class.prototype .
prototype .
:
function Rabbit() {}
let rabbit = new Rabbit();
//
Rabbit.prototype = {};
// ! (rabbit)
alert( rabbit instanceof Rabbit ); // false
: Object.prototype.toString
[object Object] :
let obj = {};
alert(obj); // [object Object]
alert(obj.toString()); //
toString . toString . typeof instanceof .
. .
-
[object Number] -
[object Boolean] -
null:[object Null] -
undefined:[object Undefined] - :
[object Array] - ( ).
:
// toString
let objectToString = Object.prototype.toString;
//
let arr = [];
alert( objectToString.call(arr) ); // [object Array]
call call/apply objectToString this=arr .
toString this . :
let s = Object.prototype.toString;
alert( s.call(123) ); // [object Number]
alert( s.call(null) ); // [object Null]
alert( s.call(alert) ); // [object Function]
Symbol.toStringTag
toString Symbol.toStringTag .
:
let user = {
[Symbol.toStringTag]: "User"
};
alert( {}.toString.call(user) ); // [object User]
. :
// : toStringTag
alert( window[Symbol.toStringTag]); // Window
alert( XMLHttpRequest.prototype[Symbol.toStringTag] ); // XMLHttpRequest
alert( {}.toString.call(window) ); // [object Window]
alert( {}.toString.call(new XMLHttpRequest()) ); // [object XMLHttpRequest]
Symbol.toStringTag ( ) [object ...] .
.
instanceof {}.toString.call .
:
typeof |
||
{}.toString |
Symbol.toStringTag |
|
instanceof |
true/false |
{}.toString typeof .
instanceof .
<code><pre>. (plnkr jsbin codepen)