typeof 是一元操作符,而instanceof是二元操作符;
typeof 操作的是一个变量,而instanceof前面是一个变量,后面是一个类型;
typeof 返回的是一个字符串,而instanceof 返回的是一个布尔值。
1、typeof()
http://www.cnblogs.com/jikey/archive/2010/05/05/1728337.html typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。 示例
结果 |
typeofhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof The 示例 // Numbers typeof 37 === 'number'; typeof 3.14 === 'number'; typeof(42) === 'number'; typeof Math.LN2 === 'number'; typeof Infinity === 'number'; typeof NaN === 'number'; // Despite being "Not-A-Number" typeof Number(1) === 'number'; // but never use this form! // Strings typeof "" === 'string'; typeof "bla" === 'string'; typeof (typeof 1) === 'string'; // typeof always returns a string typeof String("abc") === 'string'; // but never use this form! // Booleans typeof true === 'boolean'; typeof false === 'boolean'; typeof Boolean(true) === 'boolean'; // but never use this form! // Symbols typeof Symbol() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' // Undefined typeof undefined === 'undefined'; typeof declaredButUndefinedVariable === 'undefined'; typeof undeclaredVariable === 'undefined'; // Objects typeof {a:1} === 'object'; // use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new Date() === 'object'; // The following is confusing. Don't use! typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String("abc") === 'object'; // Functions typeof function(){} === 'function'; typeof class C {} === 'function'; typeof Math.sin === 'function';
|
2、instanceof
instanceofhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof The The // defining constructors function C(){} function D(){} var o = new C(); alert(o instanceof C);// true, because: Object.getPrototypeOf(o) === C.prototype alert(o instanceof D);// false, because D.prototype is nowhere in o's prototype chain alert(o instanceof Object);// true alert(C.prototype instanceof Object);// true C.prototype = {}; var o2 = new C(); alert(o2 instanceof C);//true alert(o instanceof C);// false, because C.prototype is nowhere in o's prototype chain anymore D.prototype = new C();// use inheritance var o3 = new D(); alert(o3 instanceof D);//true alert(o3 instanceof C);//true |
转载于:https://blog.51cto.com/lsieun/1844372