码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript中this

时间:2015-09-01 12:31:32      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

全局this

浏览器宿主的全局环境中,this指的是window对象。

<script type="text/javascript">

  console.log(this === window); //true

</script>

浏览器中在全局环境下,使用var声明变量其实就是赋值给thiswindow

<script type="text/javascript">

  var foo = "bar";

  console.log(this.foo); //logs "bar" console.log(window.foo); //logs "bar"

</script>

任何情况下,创建变量时没有使用var或者let(ECMAScript 6),也是在操作全局this

<script type="text/javascript">

  foo = "bar";

  function testThis() {

    foo = "foo";

  }

  console.log(this.foo); //logs "bar" testThis();

  console.log(this.foo); //logs "foo"

</script>

除了DOM的事件回调或者提供了执行上下文(后面会提到)的情况,函数正常被调用(不带new)时,里面的this指向的是全局作用域。

<script type="text/javascript">

foo = "bar";

  function testThis() {

    this.foo = "foo";

  }

  console.log(this.foo); //logs "bar"

  testThis();

  console.log(this.foo); //logs "foo"

</script>

 

JavaScript中this

标签:

原文地址:http://www.cnblogs.com/zhaoleigege/p/4775305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!