this

2016-12-21  本文已影响0人  小周师傅

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

call, apply都属于Function.prototype的一个方法,它是JavaScript引擎内在实现的,因为属于Function.prototype,所以每个Function对象实例,也就是每个方法都有call, apply属性

代码

1.以下代码输出什么?

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

输出:John:hi!

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

func() 
function func() { 
alert(this)
}

输出:window

3.下面代码输出什么

function fn0(){
      function fn(){
             console.log(this); 
      } 
      fn();
}
fn0();//window
document.addEventListener('click', function(e){   
        console.log(this); //document document DOM中谁绑定,this就是谁
        setTimeout(function(){
             console.log(this);//window   setTimeout及setInterval里的this均指window
 }, 200);
}, false);

4.下面代码输出什么,why

var john = {
 firstName: "John"
 }
function func() { 
alert( this.firstName )
}
func.call(john)
//John,当函数被call方法调用时,其this指向传入的对象,这里函数func的this就指向对象john

5.代码输出?

var john = { 
firstName: "John", 
surname: "Smith"
}
function func(a, b) {
    alert( this[a] + ' ' + this[b] )
}
func.call(john, 'firstName', 'surname')
//John Smith  函数执行时传入的this是john对象

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

var module= {
   bind: function(){
      $btn.on('click', function(){
             console.log(this) //this指的是$btn源DOM对象 
                   this.showMsg(); //这里的this指向的还是$btn源DOM,而$btn源DOM下没有showMsg()这个方法,它在对象module上
              })
    }, 
   showMsg: function(){
            console.log('饥人谷');
    }
}

修改:

var module= {
    bind: function(){
       $btn.on('click', function(){
           console.log(this) 
            module.showMsg(); //改为  module.showMsg()
 })
 },
 showMsg: function(){
 console.log('饥人谷');
 }
}
var module= {
        var  mo= this; //  把环境 this 保存下来
   bind: function(){
          $btn.on('click', function(){
          console.log(this) 
          mo.showMsg(); // 此时调用正确
 })
 },
 showMsg: function(){
        console.log('饥人谷');
 }

7.下面代码输出什么

var length = 3;
function fa() { 
     console.log(this.length);//3
}
var obj = { 
    length: 2,
   doSome: function (fn) { 
       fn();//环境this是全局window,所以为 3
       arguments[0](); //环境 this 是arguments; 相当于执行 arguments.fa(); 参数中只有一个,所以length为1;
     }
}
obj.doSome(fa) //把 fa 传入 doSome 里面的函数当参数
上一篇 下一篇

猜你喜欢

热点阅读