js 的数据类型

76 阅读1分钟

分为原始数据类型和引用数据类型

原始数据类型有 undefined null number bool string symbol bigint。

引用数据类型 function array date regexp object error generator map weakmap set weakset promise asyncfunction 等。

js 提供的判断数据类型的方法有 typeof instanceof

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

The instanceof operator tests the presence of constructor.prototype in object's prototype chain.

instanceof 判断在对象的原型链上是否可以找到constructor的原型。在原型链中存在__proto__和prototype,其中__proto__是指向构造函数的prototype的引用。 prototype 是函数的属性,用来在new的时候构造对象的__proto__。现在可以用Object.getPrototypeOf获得一个对象的原型。

instanceof的方法实现:

function instanceOf(ob1, ob2) {
   //return ob2.prototype.isPrototypeOf(ob1)
  let proto = ob1.__proto__ // Object.getPrototypeOf(ob1)
  for (;proto;) {
    if (proto === ob2.prototype) {
      return true
    }
    proto = proto.__proto__ // Object.getPrototypeOf(proto)
  }
  return false
}

new的方法实现:

function newfn(fn, ...args) {
  const temp = {}
  temp.__proto__ = fn.prototype // 这个操作会使 temp.constructor === fn
  const result = fn.call(temp, ...args)
  return result || temp
}

图示:

var b = new Foo(20);
var c = new Foo(30);

UfXRZ.png

通过原型链来判断类型的方法是: Object.prototype.toString.call().slice(8,-1).toLowerCase() 具体这个是方法是怎么运行的,需要看Object.prototype.toString 这个方式是怎么运行的。

引用:

dmitrysoshnikov.com/ecmascript/… developer.mozilla.org/en-US/docs/… developer.mozilla.org/en-US/docs/…