JavaScript的prototype是什么?

所有对象都有prototype,prototype自身也是对象,它有prototype,这样就形成了prototype链。当遇到有链中为null时,链就终止了,object的prototype就是null.

上面内容http://www.javaeye.com/article/53537有介绍,

然而有太多问题需要想明白了。

prototype它是一种数据结构,还是别的什么。

function class1(name)

{

this.class1Name=name;

}

function class2(name)

{

this.class2Name=name;

}

function class3(name)

{

this.class3Name=name;

}

class3.prototype=new class1('class1');//把一个对象class1替换(用这个词感觉不对)prototype

class3.prototype.abc='abc';然而此时还能通过prototype添加属性。 目前按照我的理解,prototype不是一个简单的对象。

class3.prototype=new class2('class2');//这一步后abc属性就不存在了。

接下来说一下对象对属性的访问。

这个是上面链接中的原话:

读操作会读取在obj自己和prototype 链上发现的第一个同名属性值

写操作会为obj对象本身创建一个同名属性(如果这个属性名不存在

这里要注意同名属性,如下

function class1()

{

this.className='class1';

}

function class2()

{}

class2.prototype=new class1();

alert(new class2().className)//这里结果为class1;说明访问到了class1中的className属性。

class2.prototype.class1=new class1();

alert(new class2().className)//这里结果为undefined,说明没有访问到className属性。

所以在属性访问上是根据属性名的,就算这个属性held的是一个对象。而不会去访问到下面的prototype中去。

下面说一下this这个关键字。

function class1(name)

{

this.user=name;

}

class1.prototype=

{

firstName:function()

{

return this.user;

}

}

function class2(name)

{

this.name=name;

}

class2.prototype=new class1('class1');

alert(new class2('class2').firstName());//这里结果应该能想到是class1.

但是如果这样写,把function class1的的代码改成如下:

function class1(name)

{

this.name=name;

}

class1.prototype=

{

firstName:function()

{

return this.name;

}

}

alert(new class2('class2').firstName());//此时输出的结果就是class2;

开始class2访问firstName方法,它便在自己成员中查找,没有找到,就在prototype中查找。这时它在class1中找到了fristName

而class1中firstName方法返回this.name,这个this指的还是class2.所以它又会在class2的成员中查找。所以这里的结果是class2;

对JavaScript一直都不太清楚,现在更迷惑了。希望明白人说一下。

另外Function 和Object是个奇怪的东西。