1. 定義類
在 javascript 中定義類的方式有好幾種, prototype 也提供了一種定義類的方法。
??? var Shape = Class.create();
??? Shape.prototype = {
?????? initialize:function(color){
?????????? this.color = color;
?????????? alert('in initialize');
?????? },
?????? draw:function(){
?????????? alert("in draw");
?????????? alert(this.color);
?????? }
??? }
??? var shape = new Shape('red');
shape.draw();
initialize
是
Shape
的構造器。
2.
類繼承
我們現在有一個 Circle 繼承了 Shape 并增加了半徑的屬性。代碼如下:
??? var Circle = Class.create();
??? Circle.prototype = Object.extend(new Shape(),{
?????? initialize:function(color,radius){
?????????? alert('in Circle initialize');
?????????? this.color = color;
?????????? this.radius = radius;
?????? },
?????? drawCircle:function(){
?????????? alert("in drawCircle");
?????????? alert("color:"+this.color);
?????????? alert("radius:"+this.radius);
?????? }
??? })
???
??? var circle = new Circle("green",10);
??? circle.drawCircle();
??? circle.draw();
Circle 內的 this.color 是從父類繼承下來的, new Circle("green",10) 的時候父類的構造函數將首先別執行,但這時的 color 的值是 undefine ,接著執行子類的構造函數 color 將被賦值為 “ green”.