1. 程式人生 > >JS——創建對象

JS——創建對象

構造器 other ast () inner .html name itl .cn

創建了對象的一個新實例,並向其添加了四個屬性:

person=new Object();//不要var
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";

替代代碼:

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

使用對象構造器:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } var tercher=new person("Bill","Gates",56,"blue");

在構造器函數內部定義對象的方法:

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.changeName("Ballmer");

循環遍歷對象的屬性:

<!DOCTYPE html>
<html>
<body>
<p>點擊下面的按鈕,循環遍歷對象 "person" 的屬性。</p>
<button onclick="myFunction()">點擊這裏</button>
<p id="demo"></p>

<script>
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; } </script> </body> </html>

結果:BillGates56

參考:JS對象創建、JS創建類和對象

JS——創建對象