js的建立對象

來源:互聯網
上載者:User

標籤:

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的建立對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.