<html lang="en"> <head> <meta charset="utf-8"> <title>prototype demo</title> </head> <body> <input type="button" value="click me" onclick="test()" /> </body> <script> function Chess(name, price){ this.name = name; this.price = price; this.setName = function(name){ this.name = name } this.getName = function(){ return this.name; } this.setPrice = function(price){ this.price = price } this.getPrice = function(){ return this.price; } Chess.prototype.CO_LTD = "娛樂科技股份有限公司"; Chess.prototype.say = function(){ return "象棋類別,軍啦!"; } } function test(){ var c = new Chess('象棋', 40); alert(c.name) alert(c.getName()); alert(c.price) alert(c.getPrice()); alert(c.say()); alert(c.CO_LTD); alert(Chess.toString());// 回傳Chess類別,為內鍵方法 } </script> </html>
Chess.prototype也可以寫在外面,如下:
function Chess(name, price){ this.name = name; this.price = price; this.setName = function(name){ this.name = name } this.getName = function(){ return this.name; } this.setPrice = function(price){ this.price = price } this.getPrice = function(){ return this.price; } } Chess.prototype.CO_LTD = "娛樂科技股份有限公司"; Chess.prototype.say = function(){ return "象棋類別,軍啦!"; }
差別在Chess.toString()就沒有Chess.prototype的程式碼了
prototype類似java的static,共用同一個空間,但呼叫不能類別.方法或屬性
this.屬性,看起來類似java的public,所以不用寫setter/getter也可以
類別裡一定要用this;呼叫時一定要用new,否則不具意義
沒有留言:
張貼留言