原生函数即JavaScript的内建函数

常用的原生函数

image.png

原生函数与构造函数

原生函数可以当做构造函数来使用,但创建出来的是封装了基本类型值的封装对象,属于对象类型

  1. var a = new String("abc")
  2. typeof a // 不是"string" 而是 "object"
  3. a instanceof String // true
  4. Object.prototype.toString.call(a) // "[object String]"

内部属性[[class]]

所有typeof返回值为"object"的对象都包含一个内部属性 [[class]],这个属性无法直接访问,一般通过Object.prototype.toString()来查看,通常与创建该对象的内建原生构造函数相对应

  1. Object.prototype.toString.call([1,2,3]) // "[object Array]"
  2. Object.prototype.toString.call(/regex-litera/i) // "[object RegExp]"

封装对象包装

包装

基本类型没有.lengthtoString()这样的属性和方法,需要通过封装对象才能访问,所以当基本类型使用这些属性和方法时,JavaScript会自动将其包装为一个封装对象

  1. var a = "abc"
  2. a.length // 3
  3. var b = 24
  4. b.toString() // "24"

拆包装 valueOf()

  1. var a = new String("abc")
  2. a.valueOf() // "abc"

👉 关于toString

每个对象都有一个 toString()方法,这个方法被每个 Object对象继承,如果此方法在自定义对象中未被覆盖,则返回的是 "[object type]",其中type是对象的类型,其中基本类型对应的type实际它的包装对象类型。

  1. Object.prototype.toString.call({}) // "[object Object]"
  2. Object.prototype.toString.call([]) // "[object Array]"
  3. Object.prototype.toString.call(function() {}) // "[object Function]"
  4. Object.prototype.toString.call('') // "[object String]"
  5. Object.prototype.toString.call(1) // "[object Number]"
  6. Object.prototype.toString.call(true) // "[object Boolean]"
  7. Object.prototype.toString.call(null) // "[object Null]"
  8. Object.prototype.toString.call(undefined) // "[object Undefined]"
  9. Object.prototype.toString.call(Symbol()) // "[object Symbol]"

覆盖从Object继承的toString方法

  • Array 对象

对于数组对象,toString方法连接数组并返回一个字符串,其中包含用逗号分隔的每个数组元素

  1. var arr = [1, 'skr', true, function() {}, {}]
  2. arr.toString() // "1,skr,true,function() {},[object Object]"
  • Function 对象

对于自定义的Function对象,toString方法返回一个字符串,其中包含用于定义函数的原文本段

  1. var func = function () {
  2. console.log('aaa')
  3. }
  4. func.toString() // "function () { console.log('aaa') }"

若this不是Function对象,则toString方法将抛出 TypeError

  1. Function.prototype.toString.call('foo') // TypeError