美文网首页
this & call & apply & bind

this & call & apply & bind

作者: BitterOutsider | 来源:发表于2020-11-20 20:51 被阅读0次

this

  • this其实就是call的第一参数
  • 一个准则xxx.meythod(),其中函数内的this就是xxx
let person = {
  name: "Ben",
  sayThis: function(){
    console.log(this)
  }
}
// person
person.sayThis(); 
let fn = person.sayThis;
// window
fn()
// {name:"Lucy"}
person.sayName.call({name:"Lucy"})

call & apply

  • call的第一个参数是this,后面的参数就是想要传入函数的参数。
function fn(){
  console.log(this)
  for(i in arguments){
    console.log(arguments[i])
  }
}
// {name:"Ben"} "hello" "js" 1 2 3
heelofn.call(undefined, "hello", "js", 1, 2, 3)
  • apply的第一个参数也是this,但是参数需要作为一个数组,当作第二个参数传入。
function fn(){
  let result = 0;
  for(i in arguments){
    result += arguments[i]
  }
  return result
}
// 15
console.log(fn.apply(undefined, [1, 2, 3, 4, 5]))

bind

  • bind会返回一个新的函数,函数内部的this就是bind传入参数
  • 一个简单的例子
let event = {
  element : $("#div1"),
  bindEvents : function(){
    let _this = this
    this.element.onClick = function(){
      _this.onClick();
    }
    
  },
  onClick: function(){
    this.element.addClass("aaa")
  }
}
let event = {
  element : $("#div1"),
  bindEvents : function(){
    this.element.onClick = this.onClick.bind(this)
  },
  onClick: function(){
    this.element.addClass("aaa")
  }
}
let event = {
  element : $("#div1"),
  bindEvents : function(){
    this.element.onClick = () => {this.onClick()}
  },
  onClick: function(){
    this.element.addClass("aaa")
  }
}

相关文章

网友评论

      本文标题:this & call & apply & bind

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