---
title: "JavaScript类和继承：this属性"
author: "xwpxcom"
date: "2011-01-15T17:04:36Z"
tags: ["Apple", "JavaScript"]
categories: ["Web前端"]
slug: "javascript-this"
draft: false
lastmod: "2011-01-15T17:04:36Z"
id: 875353
url: "https://xwpxcom.iteye.com/blog/875353"
---

this属性表示当前对象，如果在全局作用范围内使用this，则指代当前页面对象window； 如果在函数中使用this，则this指代什么是根据运行时此函数在什么对象上被调用。 我们还可以使用apply和call两个全局方法来改变函数中this的具体指向。

先看一个在全局作用范围内使用this的例子：

1. &lt;script type="text/javascript"&gt;
2. console.log(this === window);  // true
3. console.log(window.alert === this.alert);  // true
4. console.log(this.parseInt("021", 10));  // 10
5. &lt;/script&gt;

函数中的this属性是在运行时决定的，而不是函数定义时，如下：

01. // 定义一个全局函数
02. function foo() {
03. console.log(this.fruit);
04. }
05. // 定义一个全局变量，等价于window.fruit = "apple";
06. var fruit = "apple";
07. // 此时函数foo中this指向window对象
08. // 这种调用方式和window.foo();是完全等价的
09. foo(); // "apple"
10. // 自定义一个对象，并将此对象的属性foo指向全局函数foo
11. var pack = {
12. fruit: "orange",
13. foo: foo
14. };
15. // 此时函数foo中this指向window.pack对象
16. pack.foo(); // "orange"

全局函数apply和call可以用来改变函数中this属性的指向，如下：

01. // 定义一个全局函数
02. function foo() {
03. console.log(this.fruit);
04. }
05. // 定义一个全局变量
06. var fruit = "apple";
07. // 自定义一个对象
08. var pack = {
09. fruit: "orange"
10. };
11. // 等价于window.foo();
12. foo.apply(window); // "apple"
13. // 此时foo中的this === pack
14. foo.apply(pack);   // "orange"

注：apply和call两个函数的作用相同，唯一的区别是两个函数的参数定义不同。

因为在Java Script中函数也是对象，所以我们可以看到如下有趣的例子：

01. // 定义一个全局函数
02. function foo() {
03. if (this === window) {
04. console.log("this is window.");
05. }
06. }
07. // 函数foo也是对象，所以可以定义foo的属性boo为一个函数
08. foo.boo = function() {
09. if (this === foo) {
10. console.log("this is foo.");
11. } else if (this === window) {
12. console.log("this is window.");
13. }
14. };
15. // 等价于window.foo();
16. foo(); // this is window.
17. // 可以看到函数中this的指向调用函数的对象
18. foo.boo(); // this is foo.
19. // 使用apply改变函数中this的指向
20. foo.boo.apply(window); // this is window.