JavaScript使用prototype定义对象类型
JavaScript使用prototype定义对象类型
发布时间:2016-12-30 来源:查字典编辑
摘要:From:JavaEye.comprototype提供了一套JavaScript面向对象基础设施,我们可以使用它来进行面向对象编程,定义对象...

From:JavaEye.comprototype提供了一套JavaScript面向对象基础设施,我们可以使用它来进行面向对象编程,定义对象类型方式如下:

varPerson=Class.create();Person.prototype={initialize:function(name,age){this.name=name;this.age=age;},toString:function(){document.writeln("[name]:"+this.name+"<br>"+"[age]:"+this.age);}}

先使用Class.create()来创建一个对象类型,然后定义该对象类型,注意initialize方法是Person的构造器,完整的HTML如下:

复制代码 代码如下:

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>

<title>TestObject</title>

<scripttype="text/javascript"src="prototype.js"></script>

</head>

<body>

<scripttype="text/javascript"></DIV>

<DIVclass=code>varPerson=Class.create();

Person.prototype={

initialize:function(name,age){

this.name=name;

this.age=age;

},

toString:function(){

document.writeln("[name]:"+this.name+"<br>"+"[age]:"+this.age);

}

}</DIV>

<DIVclass=code>varperson=newPerson("robbin",30);

person.toString();

</script>

</body>

</html>

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类