From: 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">
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>