继承问题 :求指教

 function SuperType(){
        this.name='s;'
        this.colors = ["red", "blue", "green"];
    }
    
    function SubType(){            
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();

    var instance1 = new SubType();
    var instance2 = new SubType();
    instance1.name='ssss';
    instance1.colors=["red", "blue"];
    alert(instance1.colors);    //"red,blue,green,black"
    alert(instance1.name);      //"ssss"
    alert(instance2.colors);    //"red,blue,green,black"
    alert(instance2.name);      //"s"

instance2.name 为什么没有改变

   function SuperType(){
        this.name='sdsd';
        this.colors = ["red", "blue", "green"];
    }

    function SubType(){  
        //inherit from SuperType
        SuperType.call(this);
    }

    var instance1 = new SubType();
    instance1.colors.name='aaaaaaa'; 
    instance1.colors.push("black");
    alert(instance1.colors);    //"red,blue,green,black"
    alert(instance1.name);      //"a"
    var instance2 = new SubType();
    instance2.colors.name='bbbbbbb'; 
    alert(instance2.colors);    //"red,blue,green"
    alert(instance2.name);     //"a"

instance2.name和instance1.name 都没有改变

阅读 1.8k
2 个回答
  1. 读(console.log(a.key))和写(a.key = 1)的时候是不一样的,读的时候会一直查下去,写的时候发现本身没有就直接创建赋值了。
  2. new SubType()时this指向当前新创建的instance,所以产出为{name, colors}。那你改对colors添加name是不会影响到name属性的。

哥们 你先仔细读一遍你给出的代码,看看有没有什么问题。
我大致懂了你的意思,首先你要明白引用类型和基本类型的区别,instance1和instance2的name属性都是字符串属于基本类型,instance1.name和instance2.name在内存空间里是独立的,互不影响的。而color属性时一个数组属于引用类型,instance1.color和instance2.color中存储只是color数组的地址,也就是说两者指向的是同一个数组,因此只要color数组发生了改变,instance1.color和instance2.color得到的值都会发生改变。
举个例子吧:

var string1 = "aaa";
var string2 = string;
string1 = "bbb";
console.log(string2)    // aaa,因为string1和string2在内存中是相互独立的
var array1 = ["a","b"];
var array2= array1;
array1.push("c");
console.log(array2)    // [a,b,c],因为array1和array2是对内存中同一个数组的引用

最后,给你推荐几本书《javascript高级教程》《javascript语言精粹》《javascript忍者秘籍》,从你的问题可以看出你js基础有所欠缺,多看看书对你有帮助的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题