天天看点

值类型和引用类型

(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']

继续阅读