有这么一个类,初始化时传递2参数,分别是list组件名与addressurlvar Billing = Class.create();
Billing.prototype = {
initialize: function(listname,addressUrl){
this.addressUrl = addressUrl;
this.listname= listname;
},
save: function(){
var request = new Ajax.Request(
this.addressUrl ,
{
method: 'post',
onComplete: this.onComplete,
onSuccess: this.onSave,
parameters: Form.serialize(this.form)
}
);
}
}, onSave:function(){
alert(listname);//这里访问不到类初始化时传入的组件名称,是不是需要用闭包?
}
//访问 var billing=new Billing('billingzip','http://xxx.xxx.xxx');
billing.save();
后来我在Billing类中添加了一个函数来返回listname,还是不行,搞得我很迷惑。请各位给讲解一下原因
Billing.prototype = {
initialize: function(listname,addressUrl){
this.addressUrl = addressUrl;
this.listname= listname;
},
save: function(){
var request = new Ajax.Request(
this.addressUrl ,
{
method: 'post',
onComplete: this.onComplete,
onSuccess: this.onSave,
parameters: Form.serialize(this.form)
}
);
}
}, onSave:function(){
alert(listname);//这里访问不到类初始化时传入的组件名称,是不是需要用闭包?
}
//访问 var billing=new Billing('billingzip','http://xxx.xxx.xxx');
billing.save();
后来我在Billing类中添加了一个函数来返回listname,还是不行,搞得我很迷惑。请各位给讲解一下原因
initialize: function(listname,addressUrl){
this.addressUrl = addressUrl;
this.listname= listname;
},
save: function(){
var request = new Ajax.Request(
this.addressUrl ,
{
method: 'post',
onComplete: this.onComplete,
onSuccess: this.onSave,
parameters: Form.serialize(this.form)
}
);
}, onSave:function(){
alert(listname);//这里访问不到类初始化时传入的组件名称,是不是需要用闭包?
}
}
试试
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
};
var s = Class.create();
s.prototype = {
initialize: function(a, b) {
this.aa = a;
this.bb = b;
},
save: function() {
var _self = this;
var re = new ajax(this.aa, {
onSuccess: function() {
_self.onSave()
}
});
},
onSave: function() {
alert(this.aa);
}
}
function ajax(url, options) {
options.onSuccess();
}
var ss = new s('a.aspx', 'c=d');
ss.save();
var obj=this;
var request = new Ajax.Request(
obj.addressUrl ,
{
method: 'post',
onComplete: obj.onComplete,
onSuccess: obj.onSave,
parameters: Form.serialize(obj.form)
}
);
}
},
onSave:function(){
alert(this.listname);
}initialize函数中传入的参数listname,显然在执行完该函数就销毁掉了(闭包情况下除外)。
那么在onSave当然取不到值,肯定是undefined。
this指向最近的一个对象,在这里即Billing。在JS中this很容易改变,使用的时候要注意它所指向的对象。
看看这个http://topic.csdn.net/u/20090217/13/653f7949-9e0c-4e99-adb3-dcbc99fca8d5.html?17964