Posted on 2007-06-20 11:38
沧桑雨迢迢 阅读(281)
评论(2) 编辑 收藏 网摘 所属分类:
Javascript 、
Asp.net Ajax
在面向对象语言的编程JAVA和C#中,都有对象"索引器"的概念.如:
C#实现:

public class MyClass
{
private string _name;
//索引器

public string Name
{

get
{ return this._name;}

set
{ this._name = value; }
}
}
JAVA实现:

public class MyClass
{
private String _name;

public String getName()
{
return this._name;
}

public void setName(String value)
{
this._name = value;
}
}
在javascript中,实现索引器的方法和java差不多,如下:

var MyClass = function()
{
}

MyClass.prototype =
{
_name: null,

get_name: function()
{
return this._name;
},

set_name: function(value)
{
this._name = value;
}
}
这种javascript索引器的做法,就是MS AJAX的做法.
当我们需要访问某一对象的属性时,可以由一个专门的"属性访问方法"来统一执行,如下:
<script type="text/javascript">

var MyClass = function()
{
}

MyClass.prototype =
{
_name: null,

get_name: function()
{
return this._name;
},

set_name: function(value)
{
this._name = value;
}
}


function setProperties(component, properties)
{

for (var name in properties)
{
var val = properties[name];
var setter = component["set_" + name];

if (typeof(setter) === 'function')
{
setter.apply(component, [val]);
}
}
}

var m = new MyClass();


setProperties(m,
{name:"fanrong"});
alert(m.get_name());
</script>