this是JavaScript语言中的一个关键字

他是函数运行时,在函数体内部自动生成的一个对象, 只能在函数体内部使用.

在不同function中, this有不同的值.

1. 纯粹的函数调用.

function的最终通用用法, 属于全局性调用, 此时this 指向的是全局对象(window).

<script>
var x = 1;
function test() {
console.log(this.x);
}
test(); // 1
</script>

2. 作为对象方法的调用

function还可以最谋改革对象的方法调用. 这时 this就只这个上级对象.

    <script>
function test() {
console.log(this.x);
} var obj = {};
obj.x = 1;
obj.m = test;
obj.m(); // 1
</script>

3. constructor 构造函数调用

所谓构造函数, 就是通过这个函数, 可以生成一个新对象. 这时, this 就只这个新对象.

<script>
function Test() {
this.x = 1;
} var obj = new Test();
obj.x // 1;
</script>

4. object中function的this

这里this 指向john object. this keyword refers to the object that called the method. object in this cases is john object.

<script>
var john = {
name: 'John',
yearOfBirth: 1990,
calculateAge: function() {
console.log(this);
}
} john.calculateAge();
</script>

5. 在function中的innerFunction

在innerFunction中的this 指向window 因为 innerFunction是普通的function. default object 是window object.

    <script>
var john = {
name: 'John',
yearOfBirth: 1990,
calculateAge: function () {
console.log(this); function innerFunction() {
console.log(this);
}
innerFunction();
}
}
john.calculateAge();
</script>

http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html

最新文章

  1. css3学习--border
  2. Java集合---LinkedList源码解析
  3. Struts2中配置默认Action
  4. python堡垒机
  5. apache常见错误汇总
  6. 你好,C++(36)人参再好,也不能当饭吃!6.3 类是如何面向对象的
  7. Android_Studio 及SDK下载
  8. Linux Crontab 定时任务使用总结
  9. MYSQL Nested Join Optimization
  10. 19. Rootkit detectors (隐形工具包检测器 5个)
  11. 算法之Python实现 - 000
  12. 《DSP using MATLAB》Problem 5.1
  13. Android-Java-synchronized同步代码块的使用场景
  14. Docker 后台进程参数-------更改Docker运行根目录的方法
  15. oracle基本查询入门(一)
  16. feginclient和hystrix的配置
  17. JavaScript 学习笔记(三)
  18. jquery flexslider 轮播插件
  19. js 拼接字符串 穿参数 带有单引号
  20. 2 Python之编程语言介绍及变量

热门文章

  1. 『cs231n』视频数据处理
  2. Jenkins安装以及邮件配置
  3. ECharts学习(1)--toolbox(工具栏)
  4. ASP.NET MVC 习惯
  5. JS-图片控制-动画管理模块
  6. 小议常被忽略的a标签:visited属性的特殊用法
  7. 【转】asp.net 下的中文分词检索工具 - jieba.net
  8. 未能加载文件或程序集“LinqToExcel”或它的某一个依赖项。试图加载格式不正确的程序。
  9. vEthernet(默认交换机) 无法访问网络
  10. spring cloud 学习(一)初学SpringCloud