JavaScript 中的引用类型(Reference Type)
首先来看一段貌似JavaScript面试题的源代码(被我做了小小的改动),通过该例子来理解JavaScript中的引用类型。而后对JavaScript中的Object做了初步的学习。
1: var a={x:1};
2: var test=function(obj)
3: {
4: obj.x=2;
5: console.log("set obj.x=2 , a.x value is "+a.x);
6: a.x=5;
7: console.log("set a.x=5,obj.x value is "+obj.x);
8: obj={x:3};
9: console.log("set obj={x:3}; a.x value is "+a.x);
10: console.log("set obj={x:3};obj.x value is "+ obj.x);
11: }
12: test(a);
13: console.log(a.x);//5
"Everything" in JavaScript is an Object: a String, a Number, an Array, a Date....
1. In JavaScript, an object is data, with properties and methods.
1.1 Properties are values associated with an object.
1.2 Methods are actions that can be performed on objects.
1.3 Accessing Objects Properties and Methods(访问对象的属性和方法)
1: objectName.propertyName
2:
3: objectName.methodName()
2. Creating a Direct Instance(创建直接的实例)
2.1 定义对象
所谓"Direct”,就是Javascript不用像CSharp和Java一样必须先声明和添加属性包装器,采用objectName.propertyName=propertyValue的方式直接添加属性并赋值。
1: person=new Object();
2: person.firstname="John";
3: person.lastname="Doe";
4: person.age=50;
5: person.eyecolor="blue";
以上的定义的语法等价与下面的语法等价(using object literals):
1: person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
2.2 使用构造函数
在构建对象集合时,采用构造函数,可以快速获得更多对象的实例。
1: function person(firstname,lastname,age,eyecolor)
2: {
3: this.firstname=firstname;
4: this.lastname=lastname;
5: this.age=age;
6: this.eyecolor=eyecolor;
7: }
8: //Creating instance of person
9: var myFather=new person("John","Doe",50,"blue");
10: var myMother=new person("Sally","Rally",48,"green");
2.3 给JavaScript对象添加方法
1: function person(firstname,lastname,age,eyecolor)
2: {
3: this.firstname=firstname;
4: this.lastname=lastname;
5: this.age=age;
6: this.eyecolor=eyecolor;
7: //Adding mthods to person object
8: this.changeName=changeName;
9: function changeName(name)
10: {
11: this.lastname=name;
12: }
13: }
3. 通过Properties遍历JavaScript对象
"The JavaScript for...in statement loops through the properties of an object.”
1: var person={fname:"John",lname:"Doe",age:25};
2: var txt="";
3: for (x in person)
4: {
5: txt=txt +" "+ person[x];
6: }
7: console.log("person info:"+txt);