鍍金池/ 問答/C  HTML/ 繼承問題 :求指教

繼承問題 :求指教

 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. 讀(console.log(a.key))和寫(a.key = 1)的時候是不一樣的,讀的時候會一直查下去,寫的時候發(fā)現(xiàn)本身沒有就直接創(chuàng)建賦值了。
  2. new SubType()時this指向當前新創(chuàng)建的instance,所以產(chǎn)出為{name, colors}。那你改對colors添加name是不會影響到name屬性的。
2017年11月7日 06:39
編輯回答
莓森

哥們 你先仔細讀一遍你給出的代碼,看看有沒有什么問題。
我大致懂了你的意思,首先你要明白引用類型和基本類型的區(qū)別,instance1和instance2的name屬性都是字符串屬于基本類型,instance1.name和instance2.name在內(nèi)存空間里是獨立的,互不影響的。而color屬性時一個數(shù)組屬于引用類型,instance1.color和instance2.color中存儲只是color數(shù)組的地址,也就是說兩者指向的是同一個數(shù)組,因此只要color數(shù)組發(fā)生了改變,instance1.color和instance2.color得到的值都會發(fā)生改變。
舉個例子吧:

var string1 = "aaa";
var string2 = string;
string1 = "bbb";
console.log(string2)    // aaa,因為string1和string2在內(nèi)存中是相互獨立的
var array1 = ["a","b"];
var array2= array1;
array1.push("c");
console.log(array2)    // [a,b,c],因為array1和array2是對內(nèi)存中同一個數(shù)組的引用

最后,給你推薦幾本書《javascript高級教程》《javascript語言精粹》《javascript忍者秘籍》,從你的問題可以看出你js基礎有所欠缺,多看看書對你有幫助的

2017年6月21日 10:55