首页 > 代码库 > JS的this本质

JS的this本质

1、this究竟为何物?

1.1 全局上下文(Global context )

在全局运行上下文中(在任何函数体外部),this 指代全局对象window,无论是否在严格模式下。

 alert(this.document === document); // true alert(this === window); // true this.a = 37; alert(window.a); // 37

this默认就是指向window对象(window对象大家可以去看下DOM树,它是最顶级的)

 

1.2 顺便说下JS的"严格模式"和"非严格模式"

进入"严格模式"的标志,是下面这行语句:

"use strict";

详细介绍请看:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html

 

2、函数上下文(Function context )

在函数内部,this的值取决于函数是如何调用的。

2.1 严格模式 和 非严格模式 下直接调用

function f1(){  return this;//非严格模式下}alert(f1() == window); // true
function f2(){  "use strict"; // 标记为严格模式  return this;}alert(f2() == undefined);//true

2.2 作为对象方法

函数以对象里的方法的方式进行调用时,它们的this由调用该函数的对象进行设置。

下面的例子中,当o.f()被调用时,函数内的this即为o对象。

var o = {  prop: 37,  f: function() {    return this.prop;  }};alert(o.f()); //  37

注意,在何处或者如何定义调用函数完全不会影响到this的行为。在上一个例子中,我们在定义o的时候为其成员f定义了一个匿名函数。但是,我们也可以首先定义函数然后再将其附属到o.f。这样做this的行为也一致。

var o = {prop: 37};function independent() {  return this.prop;}o.f = independent;alert(o.f()); //  37

下面的例子:this对象紧邻原则,不去找最大的,去找最近的对象(点前面所有的)

o.b = {g: independent, prop: 42};alert(o.b.g()); // 42         此时this不看o对像,而是看0.b对象

2.3 作为一个构造函数

function C(){  this.a = 37;}var o = new C();alert(o.a); // 37function C2(){  this.a = 37;  return {a:38};}o = new C2();alert(o.a); // 38

在最后一个例子(函数C2),因为一个对象在返回期间创建,这个新对象被直接销毁(this.a)