总结各种 prototype.call | apply | bind

Vs2BPs.jpg

总结各种 JS 内置对象 call、apply、bind 的神奇用法

Object.prototype.xxx === {}.xxx // true
Array.prototype.xxx === [].xxx // true
String.prototype.xxx === ''.xxx // true
// ...

# Object

# ({}).toString.call

在 JavaScript 里使用 typeof 判断数据类型,只能区分基本类型,即:number、string、undefined、boolean、object、symbol。

对于 null、array、function、object、date 来说,使用 typeof 都会统一返回 object 字符串。

使用 ({}).toString.call 可以判断所有类型

;({}.toString.call(null)) // "[object Null]"
;({}.toString.call(undefined)) // "[object Undefined]"
;({}.toString.call('abc')) // "[object String]"
;({}.toString.call(123)) // "[object Number]"
;({}.toString.call(true)) // "[object Boolean]"
;({}.toString.call(date)) // "[object Date]"
// ...

# ({}).hasOwnProperty.call

判断一个对象是否含有某个属性

;({}.hasOwnProperty.call(true, 'a')) // false
;({}.hasOwnProperty.call(false, 'a')) // false
;({}.hasOwnProperty.call(1, 'a')) // false
;({}.hasOwnProperty.call(Symbol(), 'a')) // false
;({}.hasOwnProperty.call({ a: undefined }, 'a')) // true
;({}.hasOwnProperty.call({ a: '' }, 'a')) // true
;({}.hasOwnProperty.call({ a: null }, 'a')) // true
;({}.hasOwnProperty.call({ a: false }, 'a')) // true
;({}.hasOwnProperty.call(null, 'a')) // Uncaught TypeError: Cannot convert undefined or null to object
;({}.hasOwnProperty.call(undefined, 'a')) // Uncaught TypeError: Cannot convert undefined or null to object

# Array

# [].concat.apply

展开一个数组,chrome 69 后数组自带 flat 方法

;[].concat.apply([], [[1], [2], [3]]) // [1, 2, 3]

# [].slice.call

将一个类数组对象转换为数组

;[].slice.call({ 0: 'a', 1: 'b', length: 2 }) // ['a', 'b']
;[].slice.call({ 0: 'a', 1: 'b', length: 2 }, 0, 1) // ['a'] // 后面参数同 slice
;[].slice.call(new Set(['a', 'b'])) // [] // 无法转换 Set
Array.from(new Set(['a', 'b'])) // ['a', 'b']

# 未完待续