在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

var string1 = "aaa";
var string2 = string;
string1 = "bbb";
console.log(string2)    // aaa,因?yàn)閟tring1和string2在內(nèi)存中是相互獨(dú)立的
var array1 = ["a","b"];
var array2= array1;
array1.push("c");
console.log(array2)    // [a,b,c],因?yàn)閍rray1和array2是對(duì)內(nèi)存中同一個(gè)數(shù)組的引用

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

2017年6月21日 10:55