天天看點

值類型和引用類型

(1)值類型(基本類型):字元串(string)、數值(number)、布爾值(boolean)、undefined、null (這5種基本資料類型是按值通路的,因為可以操作儲存在變量中的實際的值)(ecmascript 2016新增了一種基本資料類型:symbol )

儲存在棧中

(2)引用類型:對象(object)、數組(array)、函數(function)

儲存在堆

function animal (name) {

// 屬性

this.name = name || 'animal';

// 執行個體方法

this.sleep = function(){

console.log(this.name + '正在睡覺!');

}

this.name1 = 'animal1';

//執行個體引用屬性

this.features = [];

function cat(name){

cat.prototype = new animal();

var tom = new cat('tom');

var kissy = new cat('kissy');

console.log(tom.name); // "animal"

console.log(tom.name1); // "animal1"

console.log(kissy.name); // "animal"

console.log(tom.features); // []

console.log(kissy.features); // []

tom.name = 'tom-new name';

tom.name1 = 'tom-new name';

tom.features.push('eat');

//針對父類執行個體值類型成員的更改,不影響

console.log(tom.name); // "tom-new name"

console.log(tom.name1); // "tom-new name"

console.log(kissy.name1); // "animal1"

//針對父類執行個體引用類型成員的更改,會通過影響其他子類執行個體

console.log(tom.features); // ['eat']

console.log(kissy.features); // ['eat']

繼續閱讀