饥人谷技术博客

this

2016-09-21  本文已影响33人  Nicklzy

apply、call 有什么作用,什么区别

fn.call(context, param1, param2...)
fn.apply(context, paramArray)

call与apply

以下代码输出什么?

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() 
//将john.sayHi()转化为.call模式,即john.sayHi.call(john),即alert(john.Name + ": hi!")
弹出John:hi!

下面代码输出什么,为什么

func() 

function func() { 
  alert(this)
}
//转化为.call模式即为func.call(),如果没有传入参数this,则默认为window对象.弹出对象window

下面代码输出什么

function fn0(){
    function fn(){
        console.log(this);
    }
    fn();
}

fn0();//fn0()-->fn.call()未输入参数this,默认为window


document.addEventListener('click', function(e){
    console.log(this);//addEventListener监听函数中默认this为触发事件的对象,即为document
    setTimeout(function(){
        console.log(this);//setTimeout的this默认为window
    }, 200);
}, false);

下面代码输出什么,why

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName )
}
func.call(john) //.call第一个参数为this,所以弹出John

代码输出?

var john = { 
  firstName: "John",
  surname: "Smith"
}

function func(a, b) { 
  alert( this[a] + ' ' + this[b] )
}//这里的this为john,所以弹出John Smith
func.call(john, 'firstName', 'surname') 

以下代码有什么问题,如何修改

var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指的是$btn对象
      this.showMsg();
    })
  },

  showMsg: function(){
    console.log('饥人谷');
  }
}

修改为

var module= {
  bind: function(){
    var _this = this;
    $btn.on('click', function(){
      console.log(this)
      _this.showMsg(); //_this指的是module
    })
  },

  showMsg: function(){
    console.log('饥人谷');
  }
}
上一篇 下一篇

猜你喜欢

热点阅读