JavaScript使用prototype定义对象类型

作者:函数茶馆

时间:2026-10-29

浏览:578

本文介绍如何利用Prototype库提供的Class.create()方法在JavaScript中定义对象类型。通过重写prototype属性并实现initialize构造器,可以创建具有特定属性和方法的自定义对象,从而实现面向对象编程的基础架构。

文章目录

使用prototype定义对象类型

来自JavaEye.com的说明指出,prototype提供了一套JavaScript面向对象基础设施,我们可以使用它来进行面向对象编程,定义对象类型方式如下:


var Person = 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Object</title>
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<script type="text/javascript"></DIV>
<DIV class=code>var Person = 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>
<DIV class=code>var person = new Person("robbin",30);
person.toString();
</script>
</body>
</html>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章