我的漫漫程序之旅

专注于JavaWeb开发
随笔 - 39, 文章 - 310, 评论 - 411, 引用 - 0
数据加载中……

Javascript动态创建get,set方法的两种写法

<HTML>
 
<HEAD>
  
<TITLE> New Document </TITLE>
 
</HEAD>

 
<BODY>
 
<script>
    
//创建一个User类
    function User(properties)
    
{
        
//遍历所有的属性
        for(var i in properties)
        
{
            
// inner function
            (function(i)
            
{
                
//get method
                this["get" + i] = function()
                
{
                    
return properties[i];
                }
;
                
//set method
                this["set" + i]  = function(val)
                
{
                    properties[i] 
= val;
                }

            }
).call(this,i);
        }

    }


    
var me = new User({name:"zdw",age:44});
    document.write(me.getname());
    me.setname(
"admin");
    document.write(
"<br />" + me.getname());
    document.write(
"<br />" + me.getage());

    
//第二种写法
    function Person(properties)
    
{
        
var _this = this;
        
for(var i in properties)
        
{
            (
function(i)
            
{
                _this[
"get" + i] = function()
                
{
                    
return properties[i];
                }


                _this[
"set" + i] = function(val)
                
{
                    properties[i] 
= val;
                }

            }
)(i);
        }

    }


    
var you = new Person({name:"admin",age:999});
    alert(you.getname() 
+ "\n" +  you.getage());
    you.setname(
"angel");
    alert(you.getname() 
+ "\n" +  you.getage());
 
</script>
 
</BODY>
</HTML>


posted on 2008-07-21 13:39 々上善若水々 阅读(3045) 评论(0)  编辑  收藏 所属分类: JavaScript


只有注册用户登录后才能发表评论。


网站导航: