call,bind,apply的方法

2021-02-10  本文已影响0人  _empty_cup

call(),bind(),apply()均可以用来改变函数的this指向
eg:

let m = 110;
let module = {
  x: 42,
  m:33,
  getX: function(a, b) {
    return this.x+a+b;
  },
getM: function(){
    return this.m;
};
let xm =  {
  name:"和丫丫",
  age:"26",
  m:22
}
module.getX.call(xm,"--","哈哈")
module.getX.apply(xm,["--","哈哈"])
module.getX.bind(xm)("--","哈哈")
module.getM.apply()    //110    apply() 的参数为空时,默认调用全局对象。
module.getM.apply(xm) //22

call()和apply() 会直接调用方法
call() 方法接受的是一个参数列表
apply() 方法接受的是一个包含多个参数的数组
apply() 的参数为空时,默认调用全局对象。
bind()返回的是一个函数,需额外调用

上一篇 下一篇

猜你喜欢

热点阅读