JavaScript使用prototype定義物件類型
來源:互聯網
上載者:User
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"></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>