this指针

2017-06-28  本文已影响0人  逍遥g

this对象是和执行上下文息息相关的一个对象,因此它也被称为执行上下文对象(context object),即激活当前执行上下文的执行上下文(an object in which context the execution context is activated)。

任何对象都可以作为执行上下文的this值,this是执行上下文的一个属性而不是某个变量对象的属性。(a this value is a property of the execution context, but not a property of the variable object.)

这个特性十分重要,因为跟变量对象不同,this值从来不会参与到标识符查询的过程,换句话说,this值是直接从执行上下文中得到的,而不会查询原型链,只有当进入执行上下文的时候,this值就已经一次确认了。

在ECMAScript中是不能给this赋值的,还是那句话,this不是变量。

在全局上下文中,this值就是指全局对象。

在函数上下文中,this的值可能是不同的,是通过调用表达式由caller提供的。

// the code of the "foo" function

// never changes, but the "this" value

// differs in every activation

function foo() {

alert(this);

}

// caller activates "foo" (callee) and

// provides "this" for the callee

foo(); // global object

foo.prototype.constructor(); // foo.prototype

var bar = {

baz: foo

};

bar.baz(); // bar

(bar.baz)(); // also bar

(bar.baz = bar.baz)(); // but here is global object

(bar.baz, bar.baz)(); // also global object

(false || bar.baz)(); // also global object

var otherFoo = bar.baz;

otherFoo(); // again global object

上一篇 下一篇

猜你喜欢

热点阅读