Posted on 2007-09-04 09:48
tearofmoscow 閱讀(959)
評論(0) 編輯 收藏
最近才了解javascript的反射機制,只知道Java中有反射機制,沒想到這腳本中也有反射機制.真是應了我的那句話"沒有做不到,只有想不到".費話不說太多,還是分享一下我的學習心得.
我們先創建一個簡單的對象.
js 代碼
- <script>"text/javascript">
- var A={
- author:"poyexinghun",
- init:function(){
- alert("load A");
- }
- }
-
- function showObject(obj){
- for(var p in obj){
- if(typeof obj[p]=="function"){
- obj[p]();
- }else if(typeof obj[p]=="string"){
- document.write(p+"--->"+obj[p]+"
");
- }
- }
- }
- showObject(A);
- </script>
注意:
typeof是用來測試數據類型的,它有六種返回值:"number," "string," "boolean," "object," "function," 和 "undefined."(不過要注意這六種返回值一定要是小寫的.我在學習的過程中就遇到過這樣的問題).
我們首先對傳進來的對象A做了一次遍歷,會得到對象中的屬性名和方法名,在用ObjectName[propertyName]查看他們的類型.
我們在看看下一個問題:
js 代碼
- <script>"text/javascript">
- var A={
- author:"poyexinghun",
- init_tiem:new Date(),
- init:function(){
- if(arguments.length == 1){
- if(typeof arguments[0] =="string"){
- alert(arguments[0]);
- }else{
- alert("args isn't string type");
- }
- }else{
- alert("load A");
- }
- }
- }
-
- function showObject(obj){
- for(var p in obj){
- if(typeof obj[p]=="function"){
- obj[p](new Date());
- }else if(typeof obj[p]=="string"){
- document.write(p+"--->"+obj[p]+"
");
- }else if(typeof obj[p]=="object"){
- document.write(p+"--->"+obj[p].getYear()+"-"+obj[p].getMonth()+"-"+obj[p].getDate()+"
");
- }
- }
- }
- showObject(A);
- A["init"]("aaaa");
- </script>
其實這個代碼塊有二個看點:
從第6行開始到第14行.
每個執行的方法中都會有一個Arguments對象,作用是獲得執行方法中的參數.有了這個東東,我們就可以寫多態的方法了.
還一個就是第30行.
其實上面那段代碼搞懂了,下面這個就知道了,其實這個是我寫文章的時候想出來的.呵呵.