为了巩固基础,我会通过实例来详细说明,让我们一起搞懂 typeof 和 instanceof。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> console.log( 'typeof 123', ':', typeof 123 ); // number console.log( "typeof 'str'", ':', typeof 'str' ); // string console.log( "typeof !'0'", ':', typeof !'0' ); // boolean console.log( "typeof new Function()", ':', typeof new Function() ); // function console.log( 'typeof myname', ':', typeof myname ); // undefined console.log( 'typeof null', ':', typeof null ); // object console.log( "typeof {name: 'hello'}", ':', typeof {name: 'hello'} ); // object console.log( "typeof [1,2,3]", ':', typeof [1,2,3] ); // object console.log( "[1,2] instanceof Array", ':', [1,2] instanceof Array ); // true console.log( "Array.isArray([1,2])", ':', Array.isArray([1,2]) ); // true console.log( "({name: 'he'}) instanceof Object", ':', ({name: 'he'}) instanceof Object ); // true console.log( "new Date() instanceof Date", ':', new Date() instanceof Date ); function Person(){} console.log( new Person() instanceof Person ); // true // 接下來是繼承 function Parent(){}; function Child(){}; function Other(){}; Child.prototype = new Parent(); let child = new Child(); console.log( child instanceof Child ); // true console.log( child instanceof Parent ); // true console.log( child instanceof Object ); // true console.log( child instanceof Other ); // false console.log( Parent.prototype.__proto__ === Object.prototype ); // true // instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。 function fun() {} console.log(typeof fun); // function console.log(fun instanceof Function); // true console.log(fun instanceof Object); // true </script> </body> </html>