任务33 - this

2017-01-16  本文已影响0人  ReedSun_QD

问答

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

代码

以下代码输出什么?

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

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

func()   //  弹出window对象

function func() { 
  alert(this)
}

下面代码输出什么

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

fn0();  //  输出window对象


document.addEventListener('click', function(e){
    console.log(this);   //  输出document对象
    setTimeout(function(){
        console.log(this);   //  输出window对象
    }, 200);
}, false);

下面代码输出什么,why

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName ) 
}
func.call(john)    //  弹出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指的是$btn
      this.showMsg();  //  $btn没有showMsg的属性,如果调用,这里会报错
    })
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}
var module= {
  bind: function(){
    var self = this;  // 先在外部将this保存成变量,再在内部调用这个变量
    $btn.on('click', function(){
      console.log(this);
      self.showMsg(); 
    })
  },

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

这样,再进行测试,发现成功输出饥人谷

修改之后测试.png
上一篇 下一篇

猜你喜欢

热点阅读