this

2016-10-20  本文已影响0人  饥人谷_罗伟恩

一、问答

二、代码

1. 以下代码输出什么?

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func //将方法func赋值给john的sayHi属性
john.sayHi() //jhon对象调用方法, 这里可看做john.sayHi.call(john),
               //由此可知道this指向john,所以执行func的弹框内容就是John:hi!
微信截图_20161020213404.png

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

func() 
function func() { 
  alert(this)
}//因为这是在全局环境下调用func()的,所以this得指向是window,可以看做func.call(), 
 //我们知道当call为空的时候,this就默认是指向window的;因此弹框是window对象
![Uploading 微信截图_20161020213850_742192.png . . .]

3. 下面代码输出什么

function fn0(){
    function fn(){
      console.log(this);
    }
  fn();
}
fn0(); //这里同理可看做fn0.call(),这个方法里面嵌套了一层,我们可以看做下面的样子
/*
    function fn(){
      console.log(this); 
  }
  function fn0(){
      fn();
  }
*/
 //fn.call()这样我们就可以知道this的指向就是window,this在对象方法里的场合只有在被调用的时候我们才能知道他的this指向哪个对象;     
微信截图_20161020213850.png
 document.addEventListener('click', function(e){
        console.log(this);//当点击事件触发,回调函数的this指向document对象
        setTimeout(function(){
            console.log(this);//指向window
        }, 200);
    }, false);

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

var john = { 
  firstName: "John" 
}
function func() { 
  alert( this.firstName )
}
func.call(john) //若是func()的话,会弹出undefined,因为this指向window,
//而这里用了原生call()的方法,call()的作用是可以改变函数的执行环境就是this,
//传进去的第一个参数就是this对象,所以弹框的内容是"John"
微信截图_20161020213731.png

5. 代码输出?

var john = { 
  firstName: "John",
    surname: "Smith"
}
function func(a, b) { 
  alert( this[a] + ' ' + this[b] )
}
func.call(john, 'firstName', 'surname') //弹框内容是John Smith
微信截图_20161020213543.png

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

var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this)  //这里的this指向$btn
      this.showMsg();//由于this指向$btn,所以$btn是没有定义showMsg这个属性的,因此会报错
    })
  },
  showMsg: function(){
    console.log('饥人谷');
  }
}

修改后的代码1

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<button>点我</button>
<script>
    var $btn = $('button') ;
    var module= {
        bind: function () {
            var tmp = this //通过变量tmp保存this,这里的this就指向module
            $btn.on('click', function () {
                console.log(tmp);
                tmp.showMsg();
            })
        },
        showMsg: function () {
            console.log('饥人谷');
        }
    };
    module.bind();

</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读