Determine the data type (instanceof)

  • Original : MDN-instanceof

  • Function : instanceofOperator constructor for detecting prototypewhether the properties appear in the prototype chain of an instance of an object.

  • Example :

function Car(make, model, year) {
    
    
  this.make = make;
  this.model = model;
  this.year = year;
}
var auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car); // true

console.log(auto instanceof Object); // true
  • Method :object instanceof constructor

    • object: An instance object.
    • constructor: A constructor
  • Description :

instanceofOperator is used to detect constructor.prototypewhether there is a parameter Objecton the prototype chain.

At the same time, the instanceofoperator can also be used to determine the data type, but it will have a little "defect", you can view the code for details.

  • Code :
/**
 * @name instanceof示例1
 * @description 检测字符串类型
 */
const simpleString = '这是简单的 String';
const newString = new String('这是 New 出来的 String');

console.log(simpleString instanceof String); // false,检查原型链会返回 undefined
console.log(newString instanceof String); // true

/**
 * @name instanceof示例2
 * @description 检测数字类型
 */
const simpleNumber = 123;
const newNumber = new Number(123);

console.log(simpleNumber instanceof Number); // false
console.log(newNumber instanceof Number); // true

/**
 * @name instanceof示例3
 * @description 检测对象类型
 */
const simpleOjbect = {
    
    };
const newObject = new Object();

console.log(simpleOjbect instanceof Object); // true
console.log(newObject instanceof Object); // true

Guess you like

Origin blog.csdn.net/weixin_43956521/article/details/111470016