JavaScript 使用 prototype 定义对象类型
本文介绍如何使用 Prototype 库提供的 Class.create() 方法在 JavaScript 中定义对象类型。通过重写 prototype 属性并实现 initialize 构造器与 toString 方法,可以构建具有特定属性和行为的自定义对象实例。
From: JavaEye.com
使用 prototype 定义对象类型
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">
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);
}
}
var person = new Person("robbin",30);
person.toString();
</script>
</body>
</html>
JavaScript怎么准确判断数据类型:typeof、instanceof与Object.prototype.toString
2026-11-05 17:09:21
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
