this

2016-11-24  本文已影响10人  饥人谷_廖珍

随着函数场合的不同,this的值会发生变化,但是this总是指向调用函数的那个对象
(1)作为函数调用(谁调用,this就指向谁)

  console.log(this);//Window
   function fn() {
      console.log(this)
 }
fn()//Window;函数被直接调用时,this绑定到全局对象

function fn1() {
    function fn2() {
       console.log(this)
   }
 }
 fn2()//Window;

(2)setTimeout、setInterval:这两个方法执行的this也是全局对象
(3)作为构造函数:所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象

  function Person(name,sex) {
          this.name=name;
          this.sex=sex;
  }
  Person.prototype.saySex=function() {
     console.log(this.sex)
}
var p1=new Person('小明','男');
 p1.saySex();//男 

(4)作为对象方法调用:在 JavaScript 中,函数也是对象,因此函数可以作为一个对象的属性,此时该函数被称为该对象的方法,在使用这种调用方式时,this 被自然绑定到该对象

    var obj1 = {
      name: 'Byron',
      fn : function(){
      console.log(this);
    }
 };

obj1.fn();

(5)DOM对象绑定事件:在事件处理程序中this
代表事件源DOM对象

练习题

(1)以下代码输出什么?

     var john = { 
          firstName: "John" 
     }
    function func() { 
        alert(this.firstName + ": hi!")
   }
   john.sayHi = func
  john.sayHi() 
 输出结果为John:hi;sayHi()作为一个对象的属性,绑定在对象john上,此时的this指向绑定的对象所以输出结果为john:hi;

(2)以下代码输出什么

        func() 

       function func() { 
         alert(this)
     }
        输出结果为window.因为此时执行func()的环境window。所  以输出结果为window

(3)以下代码输出什么

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

 fn0();//输出window,函数嵌套产生的内部函数的this不是其父函数,仍然是全局变量,因为执行环境仍然是window.



document.addEventListener('click', function(e){
console.log(this);//输出document,在事件处理程序中this代表事件源DOM对象
setTimeout(function(){
console.log(this);//输出window,setTimeout、setInterval这两个方法执行的函数this指向全局变量window。
}, 200);
}, false);

4.以下代码输出什么

   var john = { 
     firstName: "John" 
   }

    function func() { 
      alert( this.firstName )
    }
    func.call(john) //call把函数中的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,首先call将函数中的this指向了john对象,然后传入了两个参数。

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

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

     showMsg: function(){
    console.log('饥人谷');
    }
}
修改方法:
  var module= {
   bind: function(){
   var me=this;//this指向module,把this给保存下来
  $btn.on('click', function(){
    console.log(this) //this指向$btn
    this.showMsg();
    })
    },

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

猜你喜欢

热点阅读