JavaScript 的对象是可变的
对象是可变的,它们是通过引用来传递的。
以下实例的 person 对象不会创建副本:
var x = person; // 不会创建 person 的副本,是引用
如果修改 x ,person 的属性也会改变:
实例
varperson = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}varx = person;x.age = 10; // x.age 和 person.age 都会改变
new 和不 new的区别:
- 如果 new 了函数内的 this 会指向当前这个 person 并且就算函数内部不 return 也会返回一个对象。
- 如果不 new 的话函数内的 this 指向的是 window。
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
return[this.firstname,this.lastname,this.age,this.eyecolor,this]
}
var myFather=new person("John","Doe",50,"blue");
var myMother=person("Sally","Rally",48,"green");
console.log(myFather)// this 输出一个 person 对象
console.log(myMother)// this 输出 window 对象