this相关问题

2019-05-20  本文已影响0人  饥人谷_阿银
  1. apply、call 、bind有什么作用,什么区别

回答
这三个方法均可以改变调用函数的this指向

call()方法:将调用函数中的this指向call方法的第一个参数,并将call方法第一个参数之后的参数列表传入调用函数中
apply()方法:apply方法与call方法功能类似,只不过其接受的不是参数列表,而是一个数组或类数组对象
bind()方法:将this指向传入的第一个参数,并返回一个新函数
利用这三个方法可以实现类属性和自身方法的继承;同时,对于一些类数组对象,因为其并不是真正的数组,所以并不存在数组方法,因此我们可以利用apply方法,让其调用数组方法

第 2 题
以下代码输出什么?

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

回答
"John: hi!"
解析:john.sayHi()可理解为john.sayHi.call(john),即this指向john,输出即为John.firstName + ":hi!"
第 3 题
下面代码输出什么,为什么

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

回答
输出:window
该函数内的this是在全局作用域下,所以this指向window
解析:func()可理解为func.call(null),浏览器里有一条规则:
如果你传的 context 就 null 或者 undefined,那么 window 对象就是默认的 context(严格模式下默认 context 是 undefined)
因此上面的打印结果是 window。

第 4 题
下面代码输出什么

document.addEventListener('click', function(e){
    console.log(this);
    setTimeout(function(){
        console.log(this);
    }, 200);
}, false);

回答
第一个console.log(this)输出:document
第二个console.log(this)输出:window
解析:点击页面监听click事件属于方法调用,this指向事件源DOM对象,即obj.fn.apply(obj),setTimeout内的函数属于回调函数,可以这么理解,f1.call(null,f2),所以this指向window

第 5 题
下面代码输出什么,why

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName )
}
func.call(john) 

回答
"John"
call方法改变了func中this的指向,将其指向john对象

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

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

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

回答
执行console.log(this)的时候,this代表$btn
执行this.showMsg()方法时会报错,因为this指向的是$btn这个对象,而这个对象上并不存在showMsg()这个方法,因此报错;
修改方法;只需要将this指向module这个对象即可,可通过bind传入this,如下:

//修改方法一
var module= {
  bind: function(){
     var _this = this // this指是 module对象
    $btn.on('click', function(){
      console.log(this) //  this指还是 $btn
      _this.showMsg();
    })
  },

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

  showMsg: function(){
    console.log('饥人谷');
  }
}
//方法三:箭头函数
var module = {
    bind() {
        $btn.on('click', () => {
            console.log(this)
            this.showMsg();
        })
    },
    showMsg() {
        console.log('hello');
    }
}
上一篇 下一篇

猜你喜欢

热点阅读