平時業務代碼寫多了,學習又懈怠,對js的基本功能都不太熟悉了,面試答不上來,哭唧唧
判斷的是基本數據類型。node
{} | object |
[] | object |
function(){} | function |
'1' | string |
null | object |
undefined/未定義變量 | undefined |
1/NaN | number |
true | boolean |
Symbol() | symbol |
主要基於object類型的判斷。面試
假設基於React.Component建立一個類chrome
class Board extends React.Component { //... render() { console.log(this instanceof Board);// true console.log(this instanceof React.Component);// true console.log(React.Component.prototype.isPrototypeOf(this));// true console.log(this instanceof Object);// true console.log(this instanceof Game);// false } //... } class Game extends React.Component { // ... }
5個log分別是true true true true false。
基本能夠看出instanceof與原型鏈有關,MDN上的描述是The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
是否這個構造函數的prototype屬性出如今這個對象的原型鏈中。數組
若是改動了React.Component.prototype,就會出現app
console.log(this instanceof React.Component); // false
其餘🌰函數
/^\+?(\d*\.?\d{0,2})$/ instanceof RegExp; // true new Date() instanceof Date; // true
返回對象相對應的構造函數。學習
// 基礎類型 [].constructor -> [Function: Array] {}.constructor -> error let obj = {} obj.constructor -> [Function: Object] let bx = 1; bx.constructor -> [Function: Number] // 自定義類型 function g() {} let g1 = new g(); g1.constructor -> node: [Function: g] chrome console: ƒ g() {} g1.constructor === g; // true
ES5this
Object.prototype.toString.call(NaN); // [object Number] Object.prototype.toString.call(1); // [object Number] Object.prototype.toString.call(false); // [object Boolean] Object.prototype.toString.call(null); // [object Null] Object.prototype.toString.call(undefined); // [object Undefined] Object.prototype.toString.call({}); // [object Object] Object.prototype.toString.call([]); // [object Array] Object.prototype.toString.call(Symbol()); // [object Symbol] Object.prototype.toString.call(new Date()); // [object Date]
console.log(Array.isArray([]));// true console.log(Array.isArray({}));// false Array.isArray(null); // false [] instanceof Array; // true [].constructor === Array; // true Object.prototype.toString.call([]); // [object Array]
參考博客: https://blog.csdn.net/u010998803/article/details/80732942