Re: [ js ] 幾種 define class 的 patterns
※ 引述《B9 (葉酸酸)》之銘言:
: 1. 定義 function 再把 method 加到 prototype 裡面。
: function Cat(){}
: Cat.prototype.eat = function(){};
: Cat.prototype.drink = function(){};
: constructor 當然可以像下面這樣寫。
: var Cat = function(){};
: 不過我個人喜歡下面這樣寫,因為比較像傳統 OOP 定義 class 的方法:
: function Cat()
: {
: arguments.callee.prototype.eat = function(){};
: arguments.callee.prototype.drink = function(){};
: }
It's not good , every time you new a instance ,
it need to re-allocate again , and you couldn't overwrite it anyway.
Because every time you new a object,
the prototype is writing again.
(you might not need it , but it's still bad for performance.)
: > -------------------------------------------------------------------------- <
: 2. 與第一型一樣定義 function,但重新定義 prototype object。
: function Cat(){}
: Cat.prototype =
: {
: eat: function(){},
: drink: function(){}
: }
I prefer this one , it's nature and effective.
: > -------------------------------------------------------------------------- <
: 3. 在 Function 的 prototype object 中新增一個宣告 method 的 function,
: 再利用這個 function 宣告 methods。
: Function.prototype.method = function(name, fn){ this.prototype[name] = fn; };
: function Cat(){}
: Cat.method("eat", function(){});
: Cat.method("drink", function(){});
Not native enough...
but it's good to do some overwrite job or method fn queue if need.
: > -------------------------------------------------------------------------- <
: 4. 與第三型相似,但透過小小改寫,變成 chaining pattern。
: Function.prototype.method = function(name, fn){
: this.prototype[name] = fn;
: return this;
: };
: Cat.method("eat", function(){}).method("drink", function(){});
: > -------------------------------------------------------------------------- <
: 5. 如果你的 class 只有一個物件的話,可以考慮 singleton。
: var Cat =
: {
: eat: function(){},
: drink: function(){}
: };
: > -------------------------------------------------------------------------- <
: 這是 JavaScript 的美。:D
If you are talking about all the approach,
there's another way for not to use prototype ,
like
function Cat(){
this.eat = function(){};
this.drink = function(){};
}
var c1 = new Cat();
var c2 = new Cat();
(it's still bad for performance, and not extendable after it created.)
--
I am a person, and I am always thinking .
Thinking in love , Thinking in life ,
Thinking in why , Thinking in worth.
I can't believe any of what ,
I am just thinking then thinking ,
but worst of all , most of mine is thinking not actioning...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 198.203.175.175
※ 編輯: TonyQ 來自: 198.203.175.175 (03/23 03:16)
推
03/23 06:54, , 1F
03/23 06:54, 1F
→
03/23 07:52, , 2F
03/23 07:52, 2F
推
03/23 20:47, , 3F
03/23 20:47, 3F
推
03/23 21:55, , 4F
03/23 21:55, 4F
※ 編輯: TonyQ 來自: 198.203.175.175 (03/23 22:17)
※ 編輯: TonyQ 來自: 198.203.175.175 (03/23 22:18)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章