apply 和 call
在 JS 中, apply 和 call 都是用来改变函数 执行时上下文 的, 也就是改变 this 的指向.
JS 中上下文分为定义时上下文, 执行时上下文, 且上下文 this 的指向是可以改变的.
举一个栗子
new 一个人 叫 nathan, 为黄皮肤
- function Preson (name) {
- this.name = name
- }
- Preson.prototype.skinColor = 'yellow'
- Preson.prototype.say = function () {
- console.log('Hello World, My name is' + this.name + 'and my skin color is' + this.skinColor)
- }
- let nathan = new Person('nathan')
- nathan.say() // Hello World, My name is nathan and my skin color is 'yellow'
当存在另一个黑人, 需要从 nathan 的口中说出他的肤色
- let mike = {
- skinColor: 'black',
- name: 'mike'
- }
- nathan.say.apply(mike) // Hello World, My name is mike and my skin color is black
- nathan.say.call(mike) // Hello World, My name is mike and my skin color is black
- nathan.say() // Hello World, My name is nathan and my skin color is yellow
可以看出 apply 和 call 都改变了 this 中的 ** skinColor** 和 name 对应的值, 但是当我再使用 nathan 的 say() 方法时, nathan 说的还是和之前的结果是一样的
这样就可以形象的看作是, mike 让 nathan 说了话, 而不是 mike 直接变成了 nathan
apply 和 call 区别
两者的区别就是传参的方式不同
- function Preson (name) {
- this.name = name
- }
- Preson.prototype.skinColor = 'yellow'
- Preson.prototype.say = function (old, sex) {
- console.log('Hello World, My name is' + this.name + 'and my skin color is' + this.skinColor + '. I\'m a '+ sex +' and I '+ old +'years old')
- }
- let nathan = new Preson('nathan')
- nathan.say(12, 'boy')
- let mike = {
- skinColor: 'black',
- name: 'mike'
- }
- let detail = [20, 'girl']
- nathan.say.apply(mike, detail)
- nathan.say.call(mike, ...detail)
apply 除了第一个传入的改变 this 内的参数之外, 函数本身的参数使用数组的形式传入, 而 call 则是按顺序传入
在 toString() 方法没有被重写的前提下: 我写了以下的工具函数来判断数据类型, 这里只写了判断数组的, 还可以写 String object
- function isArray (data, type) {
- let t = ''
- if (arguments.length === 2) {
- t = type.toLowerCase()
- } else {
- t = 'array'
- }
- if (t === 'array') {
- if (!Array.isArray) {
- Array.isArray = function (arg) {
- return Object.prototype.toString.call(arg) === '[object Array]'
- }
- }
- return ArrayisArray(data)
- }
- }
- bind
在函数后面链式使用 bind(), 第一个参数是改变函数内部的 this 为这个参数, 后面的参数是在调用目标函数时, 预先添加到绑定函数的参数
- var module = {
- x: 42,
- getX: function(a) {
- if (a) {
- console.log(a);
- }
- return this.x;
- }
- }
- var unboundGetX = module.getX;
- console.log(unboundGetX());// output: undefined
- var boundGetX = unboundGetX.bind(module, 'arg1');
- console.log(boundGetX());
- // ouput: arg1
- // output: 42
然后多次绑定 bind 是无效的.
三者之间的区别
当你需要在函数改变上下文之后不是马上执行, 在回调时执行, 使用 bind
apply 和 call 会立即执行函数
我是看了 此人 的文章之后, 按照自己的理解再次写的这篇文章, 使自己记忆深刻, 然后有一些话也做了简单的自己理解的义译, 欢迎评论提错
peace~
author: nathan[图片上传中...(IMG_6061.JPG-daecac-1594702430431-0)]
来源: http://www.jianshu.com/p/b1fe9143e1a7