首先來看一段貌似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);