JavaScript建立對象的兩種方法和遍曆對象的屬性

來源:互聯網
上載者:User

標籤:fat   func   last   dem   ack   blog   hang   for   font   

建立新對象有兩種不同的方法:

  • 定義並建立對象的執行個體
  • 使用函數來定義對象,然後建立新的對象執行個體

1.定義並建立對象的執行個體

var person=new Object();person.firstname="John";person.lastname="Doe";person.age=50;person.eyecolor="blue"; 

或者

var person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}

2.使用函數來定義對象,然後建立新的對象執行個體

function person(firstname,lastname,age,eyecolor){    this.firstname=firstname;    this.lastname=lastname;    this.age=age;    this.eyecolor=eyecolor;}var myFather=new person("John","Doe",50,"blue");
myFather.hobby = "pingpang";//添加屬性
把方法添加到 JavaScript 對象
function person(firstname,lastname,age,eyecolor){    this.firstname=firstname;    this.lastname=lastname;    this.age=age;    this.eyecolor=eyecolor;    this.changeName=changeName;    function changeName(name){        this.lastname=name;    }}myMother=new person("Sally","Rally",48,"green");myMother.changeName("Doe");document.write(myMother.lastname);//輸出Doe

遍曆JavaScript對象的屬性

function myFunction(){    var x;    var txt="";    var person={fname:"Bill",lname:"Gates",age:56};     for (x in person){        txt=txt + person[x];    }    document.getElementById("demo").innerHTML=txt;}

 

JavaScript建立對象的兩種方法和遍曆對象的屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.