標籤:
1.關聯陣列:
var student ={
sname : "曲某某",
age : "24",
res : function(){
console.log("I‘m "+this.sname+",I‘m "+this.age);
}
}
student.res();
建立一個student對象。有兩個屬性分別是sname和age,還有一個方法叫res。
sname : "曲某某" ===屬性名稱是sname,兒屬性值是"曲某某"。
age : "24" ===屬性名稱是age,兒屬性值是"24"。
res : function(){.....} 在student裡面建立一個函數這個函數名叫res。
console.log(...); 在控制台中輸出內容。
"I‘m "+this.sname+",I‘m "+this.age 這裡面中重要的是this.sname和this.age,this指向的是student的對象的。
訪問對象中的函數或屬性:
存取方法(函數)studen.res();
訪問屬性console.log(student.sname);
//這種建立對象只能建立一次不靈活
--------------------------------------------------------------------------------------
var student =[];
student["sname"]="曲謀謀",
student["age"]=23,
student["res"]=function(){console.log("I‘m "+student["sname"]+",I‘m "+student["age"])}
student.res();
這種同上是一樣的
--------------------------------------------------------------------------------------
使用new關鍵字建立對象
function Student(sname,age){
this.sname=sname;
this.age = age;
res=function(){
console.log("I‘m "+this.sname+",I‘m "+this.age);
}
}
var stu = new Student("q",20):
stu.res();
function Student(sname,age){...} 使用function建立對象function後面跟
的是對象名,而小括弧裡面的的傳的參數
this.sname=sname;
this.age = age;
這裡面的this是指向student的sname和age。
res=function(){
console.log("I‘m "+this.sname+",I‘m "+this.age);
}
這是student對象裡的一個方法叫res();
js的建立對象