前端基础(问答24)

2016-09-02  本文已影响33人  郑哲明

keywords: this、闭包、apply、call。


apply、call用于修改函数的运行上下文,即this。

区别:apply传入的两个参数,第二个以数组形式传入;call传入多个参数,第一个为传入的this,后面的是传入函数的参数。

举例:

Array.prototype.slice.call(this,arg1,arg2,arg3...)

Array.prototype.slice.apply(this,[arg1,arg2,arg3,...])

如果传入的this为null,则this指向window。

代码

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() 

// John: hi!
func() 

function func() { 
  alert(this)
}

//window    func在win中调用,this指向window
function fn0(){
    function fn(){
        console.log(this);
    }
    fn();
}

fn0();


document.addEventListener('click', function(e){
    console.log(this);
    setTimeout(function(){
        console.log(this);
    }, 200);
}, false);


//window
//点击document后
//document
//window

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName )
}
func.call(john) 

//john  func函数内的this修改为john
var john = { 
  firstName: "John",
  surname: "Smith"
}

function func(a, b) { 
  alert( this[a] + ' ' + this[b] )
}
func.call(john, 'firstName', 'surname') 


//John Smith 
var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指什么
      this.showMsg();
    })
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}

//this.showMsg这里的this指向的是$btn,无法调用showMsg

//修改:
//function(){
//    var that  = this
//    $btn.on('click', function(){
//      console.log(this) 
//      that.showMsg();
//    })
//  }


上一篇 下一篇

猜你喜欢

热点阅读