typeof 和instanceof
生活随笔
收集整理的這篇文章主要介紹了
typeof 和instanceof
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.typeof
首先來看typeof的測試結果
1 //1.typeof 判定 非構造函數 數據類型 2 var a = '123'; //typeof a === string 3 var b = 123; //typeof b === number 4 var c = true; //typeof c === boolean 5 var d = function(){};//typeof d === function 6 var e = {}; //typeof e === object 7 var f = undefined; //typeof f === undefined 8 var g = null; //typeof g === object 9 var h = ''; //typeof h === string 10 var i; //typeof i === undefined 11 var j = []; //typeof j === object 12 結論:typeof 判定非構造函數數據類型, 能識別的類型為:string,number,boolean,function,undefined,object 13 其中對象,數組,null都判定為object,也就是說typeof不識別Array,typeof arr === Array返回值為flase 14 15 //2.typeof 判定 構造函數 數據類型 16 var a = new String('123'); //typeof a === object 17 var b = new Number(123); //typeof b === object 18 var c = new Boolean(true); //typeof c === object 19 var d = new function(){}; //typeof d === object 20 var e = new Object(); //typeof e === object 21 var f = new Array(); //typeof f === object 22 var g = new Date(); //typeof g === object 23 結論:typeof 判定構造函數數據類型全部返還object?
2.instanceof
instanceof運算符可以用來判斷某個構造函數的prototype屬性是否存在另外一個要檢測對象的原型鏈上。
實例一:普遍用法
A instanceof B :檢測B.prototype是否存在于參數A的原型鏈上.
function Ben() { } var ben = new Ben(); console.log(ben instanceof Ben);//true實例二:繼承中判斷實例是否屬于它的父類
function Ben_parent() {} function Ben_son() {} Ben_son.prototype = new Ben_parent();//原型繼承 var ben_son = new Ben_son(); console.log(ben_son instanceof Ben_son);//true console.log(ben_son instanceof Ben_parent);//true?實例三:復雜用法
function Ben() {} console.log(Object instanceof Object); //true console.log(Function instanceof Function); //true console.log(Function instanceof Object); //true console.log(Ben instanceof Function); //true console.log(String instanceof String); //false console.log(Boolean instanceof Boolean); //false console.log(Ben instanceof Ben); //false
?
轉載于:https://www.cnblogs.com/ly-blogs/p/6443142.html
總結
以上是生活随笔為你收集整理的typeof 和instanceof的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 码农的自我修炼之路-----BST
- 下一篇: [bzoj3238]差异(后缀数组+单调