js 中的call bind apply

简介

call,bind和apply都是Function上原型的方法,他们都是改变上下文this的指向。call和apply是马上生效,而bind是调用生效。

call的介绍

在MDN中定义以下数组

call()方法去调用一个具备this值得方法和传入一个数组参数app

语法函数

call(this.Arg,arg1,arg2) this.Arg:表示的是运行时的this,arg1,arg2传入的参数this

用法prototype

  1. 在数组中的应用
// 找到数组的最大值

const arr=[2,1,3,4,5];
const max=Math.max.call(null,arr);
console.log(max); //5
在这里null表明的是window对象

// push 数组
const arr1=["a","s","d","f"];
const arr2=[1,2,3,4];
//扩大arr1的数组值
Array.prototype.concat.call(arr1,arr2);
console.log(arr1)//[a,s,d,f,[1,2,3,4]]
  1. 在对象中的使用
const obj={
    name:"llz",
    say:function(){
      console.log(`你的名字是${this.name}`)
    }
}
obj.say.call(obj)//你的名字是llz
const obj3={name:"玉萍"};
obj.say.call(obj3);//你的名字是玉萍

这种写法能够使obj3也能够使用say方法,不须要在编写重复代码
  1. 在函数中的使用
const obj={name:"llz",age:18};
const info=function(name,age){
   console.log(`you name:${name},you age ${age}`)
};
info.call(obj,obj.name,obj.age)
  1. 在面向对象中的应用
var Person=function (obj){
   this.obj=obj
}
Person.prototype.say=function(){
   console.log(this.obj.name)
}
var Son=function(obj){
    Person.call(this,obj) //用call将Person的上下文替换为Son的
}
Son.prototype=new Person() // 原型链继承
var son1=new Son({name:"ii"});
son1.say()
  1. 其余应用
// 用log方法重写console.log 方法
// 用log方法打印多个参数
function log(){
   console.log.apply(console,arguments)
}

log(1,2,3)

apply 与call用法类似,这里再也不记录

bind的用法

bind 的语法与用法

在MDN 中bind(),产生一个绑定函数,第一个参数是this,后面参数是绑定函数在运行时绑定的this,下面来个小例子code

// 通常状况,咱们将对象中的方法拿出来,而保证这个方法的this绑定不变
const obj1={name:"llz"}
 const obj={
   getNum:function(){
      console.log(this.name);
   }
 }
 const nameFnc=obj.getNum.bind(obj1);
 nameFnc()

总结

1.apply 、 call 、bind 三者都是用来改变函数的this指向 2.call和apply是马上生效,而bind是调用生效对象

相关文章
相关标签/搜索