function foo的原型与prototype属性解惑

最近在研究js,疑惑也比较多。主要是被原型这个东西给弄迷糊了。 

疑惑出自于:

function foo {

  this.name = 'foo'; 

}

alert(foo.prototype === Function.prototype ); //false。 当时一直没想明白为啥foo的原型不是Function.prototype。

 

下面例子让我想当然的认为o.prototype === Function.prototype 应该为true的:

function foo() {

  this.name = 'foo';  

}

Function.prototype.sayHello = function (parent) {

  alert('hello');

};

foo.sayHello();  //alert 'hello'


当我给Function.prototype增加了一个sayHello的方法后,foo也从原型身上得到了sayHello。用调试器观察了一下,查了一下资料(包括ECMA-262 http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/ 以及 《JavaScript the good parts》第五章5.1 Pseudoclassical) ,发现foo.prototype的定义如下:

this.prototype = {constructor: this};  //这里是foo.prototype = {constructor: foo}; 

顺便做了以下测试 

alert(foo === foo.prototype.constructor);  //true

 

那foo.prototype到底是什么?这跟new关键字有密切的关系。说一下new foo()干了些什么就知道了。

var obj = {}; //定义一个新的Object

obj.[[prototype]] == this.prototype; 

//注意1:此处的this为foo,foo.prototype此时有用武之地了,给obj的原型赋值,在此用[[prototype]]表示其原型

//注意2:obj是没有prototype属性的,估计是没用吧

var other = this.apply(obj, arguments); //这部让obj.name = 'foo',即obj作为this跑了一遍foo函数

return (typeof other === 'object' && other) || that; //如果foo函数返回了一个对象,则返回该对象,否则返回obj。

 

这样就很清楚了,new foo()的时候,foo创建了一个对象,并作为其构造函数,而foo.prototype则作为新对象的原型来使用。

foo.prototype可以添加任意方法,或改为任意的对象,而不怕修改了Function.prototype(Function.prototype是所有函数的原型);

this.prototype = {constructor: this};的意义就在于,在没有手动指定foo.prototype的情况下,js指定了一个默认的原型给new出来的新对象。

posted @ 2010-11-17 17:49  Stephen.Huang  阅读(2162)  评论(4编辑  收藏  举报