JavaScript自学笔记 第8次
1.使用对象构造器来构造对象。看起来就是一个带参数的函数,但是这个函数是用来创造对象。
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } //有了构造器后,就可以像这样来创建对象。 var myFather=new person("Bill","Gates",56,"blue"); var myMother=new person("Steve","Jobs",48,"green"); |
2.在构造器里内置对象的方法。
<script> 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("Steve","Jobs",56,"green"); myMother.changeName("Ballmer"); document.write(myMother.lastname); </script> |
3. JavaScript for...in 语句循环遍历对象的属性。
<!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]; //这里的txt应该经过了3次变化,一次Bill,然后BillGates,最后BillG//ates56。 }
document.getElementById("demo").innerHTML=txt; } </script> </body> </html> |