js

apply、call、bind的应用场景

2021-07-30  本文已影响0人  我写的代码绝对没有问题

Function是函数对象的构造方法,call,apply,bind 都是函数原型上的方法 作为实例 他自身也有这三个方法

console.dir()可以显示一个对象所有的属性和方法。

image.png

圈中的为原型方法, 方块的为实例方法,另外length属性就是argument的长度。

apply、call、bind的应用场景

var obj = {
    0: 1,
    1: 2,
    length: 2
}
var arr1 = Array.prototype.slice.call(obj) // [1, 2]
var arr2 = Array.prototype.slice.apply(obj) // [1, 2]
var arr = [1, 2, 3, 4]

//取最大值
console.log(Math.max.apply(Math, arr)) // 4
console.log(Math.max.call(Math, ...arr)) // 4

//取最小值
console.log(Math.min.apply(Math, arr)) // 1
console.log(Math.min.call(Math, ...arr)) // 1
function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]'
}
isArray([1]) // true
isArray({}) // false
class MyCircle extends Component {
    constructor(props) {
        super(props)
        this.func = this.func.bind(this)
    }
    func() {
        ...
    }
    ...
}

总结

三者作用都是改变函数this的指向
三者第一个传参都是要this要指向的对象
apply、call是立即执行函数,bind需要再次调用

拓展:
什么是伪数组

伪数组是一个含有length属性的json对象

{
    0: 1,
    1: 2,
    length: 2
}
常见的伪数组

arguments、NodeList、HTMLCollection、Jquery对象…

伪数据如何转成标准数组

使用Array.slice

function toArray() {
    console.log(arguments instanceof Array) // false
    arguments = Array.prototype.slice.call(arguments)
    console.log(arguments instanceof Array) // true
    return arguments
}
toArray(1,2,3) // [1, 2, 3]

参考文章
https://segmentfault.com/a/1190000018195263
https://segmentfault.com/a/1190000016547703?utm_source=sf-similar-article

上一篇下一篇

猜你喜欢

热点阅读