我用js写了一个类
function AA(name){
this.name = name;
this.obj=new Object();
}AA.prototype.onclick = function(){
var str="Hello:";
this.obj.onchange = function()
{
alert(this.name);//我在这个地方想调用AA中的this.name.报错,说没有定义,我应该怎样才能访问到AA中的this.name呢?谢谢
}
};
function AA(name){
this.name = name;
this.obj=new Object();
}AA.prototype.onclick = function(){
var str="Hello:";
this.obj.onchange = function()
{
alert(this.name);//我在这个地方想调用AA中的this.name.报错,说没有定义,我应该怎样才能访问到AA中的this.name呢?谢谢
}
};
AA.prototype.onclick = function() {
var str = this.name;
alert(str);
};
this.obj.onchange = function()
{
alert(this.name);//我在这个地方想调用AA中的this.name.报错,说没有定义,我应该怎样才能访问到AA中的this.name呢?谢谢
}
alert后面的this指的是this.obj.onchange = function()这个this的
而不是function AA(name)这个要搞清楚,要搞明白this的作用域。
this.obj.onchange 事件中去获取上面的this.name
var str = this.name;
this.obj.onchange = function()
{
alert(str );
}
这样就行了啊
你先在这个function中获取到父母的信息
下面怎么用都行的
function AA(name){
this.name = name;
this.obj=new Object();
}AA.prototype.onclick = function(){
var str="Hello:";
this.obj.onchange = (function()
{
alert(this.name);
}).apply(this); //调用 apply 方法,设置 onchange 方法内的 this 指向 AA 本身。
}; var a = new AA('a');
a.onclick();
a.obj.onchange();