MozTW 討論區
https://forum.moztw.org/

JavaScript回傳複數值
https://forum.moztw.org/viewtopic.php?f=13&t=17865
1 頁 (共 1 頁)

發表人:  legnaleurc [ 2007-03-06, 11:20 ]
文章主題 :  JavaScript回傳複數值

js有辦法做到回傳兩個不同型態的值嗎?
目前想到的是在回傳的變數下新增幾個物件
就像是C++的class或structure那樣
不過想不到要怎麼做

new Object()?

發表人:  yuoo2k [ 2007-03-06, 16:53 ]
文章主題 : 

[url=http://developer.mozilla.org/zh_tw/docs/重新介紹_JavaScript#.E8.87.AA.E8.A8.82.E7.89.A9.E4.BB.B6]A re-introduction to JavaScript: Custom Objects[/url]
代碼:
function makePerson(first, last) {
    return {
        first: first,
        last: last
    }
}
function personFullName(person) {
    return person.first + ' ' + person.last;
}
function personFullNameReversed(person) {
    return person.last + ', ' + person.first
}

> s = makePerson("Simon", "Willison");
> personFullName(s)
Simon Willison

> personFullNameReversed(s)
Willison, Simon

發表人:  kourge [ 2007-03-06, 17:36 ]
文章主題 : 

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。

發表人:  legnaleurc [ 2007-03-06, 20:40 ]
文章主題 : 

感謝兩位的回答
這麼看起來,原始的JavaScript並沒有class的概念嗎?

發表人:  kourge [ 2007-03-07, 13:29 ]
文章主題 : 

legnaleurc 寫:
感謝兩位的回答
這麼看起來,原始的JavaScript並沒有class的概念嗎?

JavaScript 並不是像 Java 一樣的 class-based 語言,而是 prototype-based 的語言。可以實作 class 是靠 prototype 的模式。

1 頁 (共 1 頁) 所有顯示的時間為 UTC + 8 小時
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/