使用this 和prototype,可以實現JavaScript的對象化編程,構建類和實例的概念。首先類是對象的抽象,實例則是實際的對象,用關鍵字new可以實例化對象。
this用於從實例本身的程序代碼內訪問實例,prototype對象用於設定隸屬於類層(class level)的特性和方法,而非隸屬於實例的。讓方法可以存儲於類內部,以免實例不必要地一直復制程序代碼。
以下是一個簡單的實現:
<html>
<head>
<script>
function Person(id, name){
this.id = id;
this.name = name;
}
Person.prototype.showme = function(){
return "id=" + this.id + "; name=" + this.name;
}
function test() {
var p = new Person(1, "jim");
var p2 = new Person(2, "kate");
alert(p.showme() + "\n" +p2.showme());
}
</script>
</head>
<body>
<input type="button" value="test" onclick="test()"/>
</body>
</html>
本文出自 “匚簡” 博客