prototype 關鍵字可以為 JS原有物件 或 自己建立的類別 中新增方法或屬性。 也可以實現繼承。 範例: 複製程式碼 程式碼如下: JS中prototype 關鍵字的使用 <BR><!-- demo1 JS中原有物件中新增方法--> <BR>Number.prototype. add = function (num){ <BR>return this num; <BR>} <BR>function but1_click(){ <BR>alert((3).add(8)); <BR>} <BR><! -- demo2 JS中新物件中, 新增屬性,方法--> <BR>function Car(cColor,cWeight){ <BR>this.cColor = cColor; <BR>this.cWeight = cWeight; <BR>} <BR>Car.prototype.drivers = new Array('zhangsan','lisi'); <BR>Car.prototype.work = function (cLong){ <BR>alert("我跑了" cLong "公里"); <BR>} <BR>function but2_click(){ <BR>var c = new Car("red","5"); <BR>c.drivers.push('zhaoliu'); <BR>alert(c .drivers); <BR>c.work(1); <BR>} <BR><!-- demo3 JS中新建物件中, 新增屬性,方法緊湊的寫法--> <BR>function Rectangle(rWeight, rHeight){ <BR>this.rWeight = rWeight; <BR>this.rHeight = rHeight; <BR>if( typeof this._init == 'undefined'){ <BR>Rectangle.prototype.test = function (){ <BR>alert("test"); <BR>} <BR>} <BR>this._init = true; <BR>} <BR>function but3_click(){ <BR>var t = new Rectangle(6, 8); <BR>t.test(); <BR>} <BR><!-- demo4 prototype 繼承--> <BR>function objectA(){ <BR>this.methodA = function (){ <BR>alert("我是A方法"); <BR>} <BR>} <BR>function objectB(){ <BR>this.methodB = function (){ <BR>alert("我是B方法") ; <BR>} <BR>} <BR>objectB.prototype = new objectA(); <BR>function but4_click(){ <BR>var t = new objectB(); <BR>; 🎜>t.methodA(); <BR>} <BR> prototype 關鍵字的使用