IT技术及科技前沿

中文IT博客,为IT专业技术人员提供最全面的信息传播和服务

首页 新随笔 订阅 管理

 

它是用Javascript写好的一些API,包括对Javascript中的类如String,Array等进行的扩充。

把prototype当函数用就行了。写js一般是写函数, 但某些功能直接写prototype复用性高。

prototype是用于对原型对象的继承,主要是为了节省内存空间。

 

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


然而有太多问题需要想明白了。
prototype它是一种数据结构,还是别的什么。
function class1(name)
{
   this.class1Name=name;
}
function class2(name)
{
   this.class2Name=name;
}
function class3(name)
{
   this.class3Name=name;
}
class3.prototype=newclass1('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(newclass2().className)//这里结果为class1;说明访问到了class1中的className属性。
class2.prototype.class1=new class1();
alert(newclass2().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()
      {
         returnthis.name;
      }
}

alert(new class2('class2').firstName());//此时输出的结果就是class2;
开始class2访问firstName方法,它便在自己成员中查找,没有找到,就在prototype中查找。这时它在class1中找到了fristName
而class1中firstName方法返回this.name,这个this指的还是class2.所以它又会在class2的成员中查找。所以这里的结果是class2;

对JavaScript一直都不太清楚,现在更迷惑了。希望明白人说一下。
另外Function 和Object是个奇怪的东西。

 

下面用一个简单的例子说明一下:

<html>
  <head>
      <title>标题页</title>
      <script type=text/javascript>
      // 自定义数组删除方法
      Array.prototype.del =function(n)
      {
           if (n<0) return this;
           return this.slice(0,n).concat(this.slice(n+1, this.length));
      }
      var arr = new Array("1", "2", "3", "4"); //定义4个元素的数组
      alert(arr.del(1))  //删除数组中第二个元素-从0开始索引
       //-->
     </script>
</head>
<body>
</body>
</html>

上面是一个删除数组中指定元素的脚本代码,其中的prototype是继承了Array(Array可以看做是一个类)对象,del为对象的一个属性,给del这个属性赋予了一个函数体,函数体中的this关键字指的就是prototype这个对象(即:Array这个类对象),我们可以在return this;语句之前写一句alert(this);会发现弹出来的值就是Array这个数组的所有值。this关键字有slice方法,slice方法在字符串中被应用为截取函数,而slice方法在Array类对象中的含义为从某个已有的数组返回选定的元素。综上所述,在后面初始化了一个Array类对象,因为Array.prototype.del是全局的,所以用这个arr类对象直接就可以调用del方法了。

posted on 2010-12-25 23:06  孟和2012  阅读(207)  评论(0)    收藏  举报