instanceof , , .
. , - .
instanceof
:
obj instanceof Class
true, obj Class .
:
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).true,false, .instanceof.:
// instanceof , // canEat - Animal 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.hasInstance. : ,Class.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), true, objA - objB. 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 ...].
typeof , , , .
{}.toString.call instanceof , , .
, :
typeof |
||
{}.toString |
, , Symbol.toStringTag |
|
instanceof |
true/false |
, {}.toString , typeof.
instanceof , .
<code>, —<pre>, 10 — (plnkr, JSBin, codepen)