创建JavaScript对象

1、创建直接对象实例

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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>

上面代码等效于:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!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、使用函数来构造对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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>

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

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


3、把方法添加到 JavaScript 对象

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!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





     本文转自stock0991 51CTO博客,原文链接:http://blog.51cto.com/qing0991/1394347,如需转载请自行联系原作者





上一篇:NotSupportedException-无法将类型“System.DateTime”强制转换为类型“System.Object”


下一篇:Tablestore在本地生活用户圈选场景下的分析实践