【百度分享】javascript中函数调用过程中的this

在函数的调用中,this是个什么东西,又是由什么决定的呢?在ecma262中,这是个比较绕的东西,其描述散落在世界各地。
首先,在10.2.3中告诉我们: The caller provides the this value. If the this value provided by the caller is not an object (note that null is not an object), then the this value is the global object. 我们可以知道,caller可以提供给我们this。如果没有提供,则this为global object。问题又来了,caller是怎么提供this的?
在11.2.3中,找到如下关于Function calls的描述:The production CallExpression : MemberExpression Arguments is evaluated as follows:
  1. Evaluate MemberExpression.
  2. Evaluate Arguments, producing an internal list of argument values (see 11.2.4).
  3. Call GetValue(Result(1)).
  4. If Type(Result(3)) is not Object, throw a TypeError exception.
  5. If Result(3) does not implement the internal [[Call]] method, throw a TypeError exception.
  6. If Type(Result(1)) is Reference, Result(6) is GetBase(Result(1)). Otherwise, Result(6) is null.
  7. If Result(6) is an activation object, Result(7) is null. Otherwise, Result(7) is the same as Result(6).
  8. Call the [[Call]] method _disibledevent=>} 
function B(){ 
  this.testB = new Function(); 

 
var a = new A(); 
 
B.prototype = a; 
//a.[[prototype]] == {};(不是真的等,{}表示的是Function A初始的prototype object。下同) 
 
var b = new B(); 
//b.[[prototype]] == a; 
//b.[[prototype]].[[prototype]] == a.[[prototype]] == {}; 
 
A.prototype = b; 
 
var a2 = new A(); 
//a2.[[prototype]] == b; 
//a2.[[prototype]].[[prototype]] == b.[[prototype]] == a; 
//a2.[[prototype]].[[prototype]].[[prototype]] == b.[[prototype]].[[prototype]] == a.[[prototype]] == {}; 
 
//最后测试一下,很搞笑的 
alert(a instanceof A); 
最后特殊的解释:好吧,上面代码的最后出现了很搞笑的事情,合乎语言的实现,但不合乎正常以及不正常地球人的逻辑。 我们知道,a对象是被A构造器创建出来的,所以a是A的实例。 但是,上面类型判断那里有讲,instanceof是通过构造器prototype成员与对象原型链的比较来判断的。所以当对象a被创建后,如果创建它的构造器的prototype发生了变化,a就和他妈(构造器)没任何关系了。 看到这里,你确定你还想要在实例化对象后,修改构造器的prototype成另外一个对象吗?
Tags: 

延伸阅读

最新评论

发表评论