this

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

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

  • 区别

  • 相同点:两个方法产生的作用是完全一样的

  • 不同点:方法传递的参数不同,apply接受的是数组(或者是类数组对象),call接受的是多个参数。

  • 作用
    两者都是在指定this值和参数(参数以数组或类数组对象的形式存在)的情况下调用某个函数。实际上就是说用它可以绑定一个函数然后在另一个环境中(比如另一个函数中)使用新环境给的参数(指定this值、参数)进行运算;

代码

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

推荐阅读更多精彩内容