原生函数即JavaScript
的内建函数
常用的原生函数
原生函数与构造函数
原生函数可以当做构造函数来使用,但创建出来的是封装了基本类型值的封装对象
,属于对象类型
var a = new String("abc")
typeof a // 不是"string" 而是 "object"
a instanceof String // true
Object.prototype.toString.call(a) // "[object String]"
内部属性[[class]]
所有typeof
返回值为"object"
的对象都包含一个内部属性 [[class]]
,这个属性无法直接访问,一般通过Object.prototype.toString()
来查看,通常与创建该对象的内建原生构造函数相对应
Object.prototype.toString.call([1,2,3]) // "[object Array]"
Object.prototype.toString.call(/regex-litera/i) // "[object RegExp]"
封装对象包装
包装
基本类型没有.length
、toString()
这样的属性和方法,需要通过封装对象才能访问,所以当基本类型使用这些属性和方法时,JavaScript会自动将其包装为一个封装对象
var a = "abc"
a.length // 3
var b = 24
b.toString() // "24"
拆包装 valueOf()
var a = new String("abc")
a.valueOf() // "abc"
👉 关于toString
每个对象都有一个 toString()
方法,这个方法被每个 Object对象
继承,如果此方法在自定义对象中未被覆盖
,则返回的是 "[object type]"
,其中type是对象的类型,其中基本类型对应的type实际它的包装对象类型。
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call(function() {}) // "[object Function]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
覆盖从Object继承的toString方法
Array
对象
对于数组对象,toString方法连接数组并返回一个字符串,其中包含用逗号分隔的每个数组元素
var arr = [1, 'skr', true, function() {}, {}]
arr.toString() // "1,skr,true,function() {},[object Object]"
Function
对象
对于自定义的Function
对象,toString方法返回一个字符串,其中包含用于定义函数的原文本段
var func = function () {
console.log('aaa')
}
func.toString() // "function () { console.log('aaa') }"
若this不是Function对象,则toString方法将抛出 TypeError
Function.prototype.toString.call('foo') // TypeError