JavaScript 中所有的事务都是对象,比如 String, Date, Array等等。
对象只是带有属性和方法的特殊数据类型
例
<html>
<body>
<script>
var message = "Hello World!";
var x = message.length;
alert(x);
</script>
</body>
</html>
创建JavaScriptduixiang对象
创建直接的实例
<html>
<body>
<script>
person = new Object();
person.firstname = "bill";
person.lastname = "Gates";
person.age = 56;
person.eyecolor = "blue";
document.write(person.firstname + " is " + person.age + " years old");
</script>
</body>
</html>
<html>
<body>
<script>
person = {firstname:"bill",lastname:"gates", age:56, eyecolor:"blue"};
document.write(person.firstname + " is " + person.age + "years old");
</script>
</body>
</html>
使用对象构造器
<html>
<body>
<script>
function person(firstname, lastname,age,eyecolor)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
}
myFather = new person("bill", "gates", 56, "blue");
document.write(myFather.firstname + " is " + myFather.age + " years old");
</script>
</body>
</html>
for in 遍历对象中的属性
<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>