前端基础(问答24)


keywords: this、闭包、apply、call。


  • 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
  • 下面代码输出什么,why


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();
//    })
//  }


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容