typeof、instanceOf、hasOwnProperty的使用和区别

一. typeof操作符

typeof操作符用于返回正在使用值的类型

typeof 返回值有六种可能: "number," "string," "boolean," "object," "function," 和 "undefined."以及'symbol'

null,array,object返回的都是‘object’

值类型(基本类型):字符串(String)、数字(Number)、布尔(Boolean)、对空(Null)、未定义(Undefined)、Symbol。

引用数据类型:对象(Object)、数组(Array)、函数(Function)。

ES6 中新增了一种 Symbol 。这种类型的对象永不相等,即始创建的时候传入相同的值,可以解决属性名冲突的问题,做为标记。

    

typeof使用场景

(1)、判断某个值是否已经定义

// 判断
if (typeof bbb === 'undefined') {
    console.log('变量未定义');
}

 (2)、判断是Array还是Object或者null(也可以使用instanceof进行判断)  

let getDataType = function(o){
    if(o===null){
        return 'null';
    }
    else if(typeof o == 'object'){
        if( typeof o.length == 'number' ){
            return 'Array';
        }else{
            return 'Object';   
        }
    }else{
        return 'param is no object type';
    }

(3)、判断是否是复杂值

因为复杂值往往返回object,当然有个例外就是原始值里面的null也返回object,然后function作为Object的实例也是复杂值。

// 判断是否时复杂值(对象值)
function isObject (m) {
    return (typeof m === 'function' || (typeof m === 'object' && m !== null));
}

   

二. instanceof操作符

通过使用instanceof操作符,可以确定一个对象是否是特定构造函数实例,返回truefalse

instanceof只适用于构造函数创建返回的复杂对象实例

任何时间判断一个对象(复杂值)是否是Object的实例时,它都将返回true,因为所有对象都继承自Object()构造函数。

 例如:以下例子,判断得出对象‘oSon’ 的实例是‘oFather’的实例 

let oFather = function () {
    this.firstName = 'mazey';
};
// 实例
let oSon = new oFather();
console.log(oSon instanceof oFather); // true

  

instanceof使用场景

(1)、判断是Array还是Object或者null

let getDataType = function(o){
    if(o===null){
        return 'null';
    }
    if(o instanceof Array){
        return 'Array'
    }else if( o instanceof Object ){
        return 'Object';
    }else{
        return 'param is no object type';
    }
}

(2)、判断在一个继承关系中实例是否属于它的父类。

// 继承
let oFather = function () {};
let nFather = function () {};
nFather.prototype = new oFather();
nFather.construction = nFather;

let nSon = new nFather();
console.log(nSon instanceof nFather); // true
console.log(nSon instanceof oFather); // true

  

二.hasOwnProperty方法

hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)。

var o = new Object();
o.prop = 'exists';

function changeO() {
  o.newprop = o.prop;
  delete o.prop;
}

o.hasOwnProperty('prop');  // true
changeO();
o.hasOwnProperty('prop');  // false

  

参考文章:https://www.cnblogs.com/mazey/p/7965733.html

原文地址:https://www.cnblogs.com/luoxuemei/p/14662393.html