this & call & apply & bind

2020-11-20  本文已影响0人  BitterOutsider

this

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

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)
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

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")
  }
}
上一篇下一篇

猜你喜欢

热点阅读