创建JavaScript对象

1、创建直接对象实例

示例:创建了对象的一个新实例,并向其添加了四个属性。

<!DOCTYPE html>
<html>
<body>
<!-- 创建对象 -->
<script>
person=new Object();
person.firstname="Bill";
person.lastname="Gates";
person.age=60;
person.eyecolor="green";
</script>
<!-- 使用对象 -->
<script>
    document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>

上面代码等效于:

<!DOCTYPE html>
<html>
<body>
<!-- 创建对象 -->
<script>
person={firstname:"Bill",lastname:"gates",age:60,eyecolor:"blue"}
</script>
<!-- 使用对象 -->
<script>
    document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>

输出结果:

   Bill is 60 years old.


2、使用函数来构造对象

<!DOCTYPE html>
<html>
<body>
<!-- 创建对象 -->
<script>
    function person(firstname,lastname,age,eyecolor)
    {
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
    }
</script>
<!-- 使用对象 -->
<script>
    myFather=new person("Bill","Gates",60,"blue");
    document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html>

   一旦您有了对象构造器,就可以创建新的对象实例,就像这样:

var myFather=new person("Bill","Gates",60,"blue");
var myMother=new person("Steve","Jobs",48,"green");


3、把方法添加到 JavaScript 对象

   方法只不过是附加在对象上的函数。在构造器函数内部定义对象的方法:

<!DOCTYPE html>
<html>
<body>
<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;
}
}
</script>
<script>
myMother=new person("Steve","Jobs",56,"green");
myMother.changeName("Ballmer");
document.write(myMother.lastname);
</script>
</body>
</html>

运行结果:

   Ballmer






本文出自 “IT技术学习与交流” 博客,谢绝转载!

你可能感兴趣的:(JavaScript,对象)