本文介绍如何使用 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>