typeof、instanceof和constructor

1.js to determine whether the object often uses these three keywords or attributes. The following introduces them one by one:

    (1) The typeof operator, which usually returns: "undefined", "object", "boolean", "number" and "string" strings. Both arrays and objects return "object". The typeof of arrays and objects returns the same "object" .

var o = {age: 20}; typeof o  //"object"
var a = [1,2,3]; typeof a   //"object"
var n = 20; typeof n   //"number"
var b; typeof b   //"undefined"
var f = false; typeof b   //"boolean"
var s = 'str'; typeof s   //"string"

  (2) The instanceof operator is used to determine whether the object pointed to by the prototype property of a constructor exists on the prototype chain of another object to be detected. Arrays and objects can be distinguished .

var a = {s:2}; a instanceof Object   //true

var a = [2]; a instanceof Object  //true
var a = [2]; a instanceof Array  //true

var a = 1; a instanceof Number   //false
var a = new Number(1); a instanceof Number   //true

var a = '3'; a instanceof String   //false
var a = new String('3'); a instanceof String    //true

function Person(){};
var p =new Person();
console.log(p instanceof Person);  //true

 

  (3) The constructor returns a reference to the array function that created this object. Arrays and objects can be distinguished .

//用法一:
var a = {name:2}; a.constructor === Object    //true
var a = [1,2]; a.constructor === Object    //false
var a = 1; a.constructor === Number    //true
var a = 'test'; a.constructor === String    //true
var a = new Date();a.constructor === Date    //true

//用法二:
function employee(name,job,born) {
    this.name=name;
    this.job=job;
    this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
document.write(bill.constructor);

function employee(name,job,born) {
    this.name=name;
    this.job=job;
    this.born=born;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326002774&siteId=291194637