legnaleurc 寫:
js有辦法做到回傳兩個不同型態的值嗎?
目前想到的是在回傳的變數下新增幾個物件
就像是C++的class或structure那樣
不過想不到要怎麼做
new Object()?
利用 Object,JS 也可以做出類似像 class 一樣的結構
function Blah(rant) {
this.string = rant;
};
Blah.prototype = {
getRant: function() {return this.string;},
showRant: function() {alert(this.string);}
};
>> var x = new Blah('ha ha!');
>> x.string
"ha ha!"
>> x.getRant()
"ha ha!"
>> x.showRant() //這時應該會 alert() 出 ha ha!
這是最最最最最最最簡單的 class 型式~假如
真的想用 class 的話:
1. 如果你用 Prototype,請:
var Blah = Class.create();
Blah.prototype = {
initialize: function(rant) {this.string = rant;},
getRant: function() {return this.string;},
showRant: function() {alert(this.string);}
};
2. 其他者,請用
Dean Edwards 的 Base(+
後來的更新):
引用 Base.js 以後:
var Blah = Base.extend({
constructor: function(rant) {this.string = rant;},
getRant: function() {return this.string;},
showRant: function() {alert(this.string);}
});
目前 Base 是最完整的 JS class 實作,連 inheritance 還有 method overloading 都支援了,連 Prototype 的作者都表示 Prototype 2.0 的 Class.create() 也會用 Base。