美文网首页
call,bind,apply的方法

call,bind,apply的方法

作者: _empty_cup | 来源:发表于2021-02-10 17:51 被阅读0次

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()返回的是一个函数,需额外调用

相关文章

网友评论

      本文标题:call,bind,apply的方法

      本文链接:https://www.haomeiwen.com/subject/qtjkxltx.html