function test()
{
    test.prototype.color=["red","yellow"];
}
var q1=new test();
q1.color.push("green");
alert(q1.color);  //red ,yellow,green
var q2=new test();
alert(q2.color);//red,yellow和function test()
{
    test.prototype.color=["red","yellow"];
}
var q1=new test();
var q2=new test();
q1.color.push("green");
alert(q1.color);  //red ,yellow,green
alert(q2.color);//red,yellow,green谁能给我解释下为什么两次显示不一样?

解决方案 »

  1.   

    这个 prototype.color = [];其实是共享属性(在这里我强烈建议属性和私有数据不要这样定义)第一个是因为你在q2的时候new test()了
    prototype.color恢复了原属性值第二个是因为共享属性(就是第一行给你解释的)
      

  2.   

    第一行代码加上句 供你理解function test()
    {
      test.prototype.color=["red","yellow"];
    }
    var q1=new test();
    q1.color.push("green");
    alert(q1.color); //red ,yellow,green
    var q2=new test();
    alert(q2.color);//red,yellow
    alert(q1.color);
      

  3.   

    那prototype对象是什么时间构建的,是test类型加载到内存中时就产生,还是实例test的时候产生
      

  4.   

    我在读javascript高级程序设计,其中有这句
    Whenever a function is created, its prototype property is also created according to a specific set of rules.
    由于英语不是很强,所以问问。
      

  5.   

    prototype是原型链
    关于这点你需要费些时间理解理解 这个不是那么容易就彻底弄懂的~~找些相关资料看看~~~有什么不懂的可以具体问prototype不是什么时候构建的。而是这个链上的所有属性在其对象构造之后就可以拥有其上的所有属性和方法了
    但这些属性和方法是公有的 而非私有的你在第二次new的时候改变了color 属性
    之前的对象的color属性也同时被改变了
      

  6.   

    Whenever a function is created, its prototype property is also created according to a specific set of rules.
    当函数被创建(比如你NEW的时候),它的prototype属性也会依据某个特定规则被创建。象1楼所说,new test()后 prototype.color也被重新创建,所以恢复了原设置值
      

  7.   

    to CJ & theforever:
    function test()
    {
      test.prototype.color=["red","yellow"]; 
    }
    var q1=new test();
    q1.color.push("green");
    alert(q1.color); //red ,yellow,green
    var q2=new test();
    alert(q2.color);//red,yellow这里test.prototype.color=["red","yellow"]; 到底算什么啊???function test()
    {
      //test.prototype.color=["red","yellow"];  // 这个写里面是什么意思?麻烦解释一下
    }
    test.prototype.color=["red","yellow"];      // 把这个写外面是作为共享属性了,这个我理解var q1=new test();
    q1.color.push("green");
    alert(q1.color); //red ,yellow,green
    var q2=new test();
    alert(q2.color); // red,yellow,green   // 这样 q1.color 和 q2.color 一样了