我看网上一段关于拖拽的代码,其中一部分如下:
var Class = {
create: function(){
return function(){this.initialize.apply(this,arguments);}
}
}var Drag = Class.create();
Drag.prototype={
initialize:function(arg1,arg2){
//函数体省略
}
}我还是不怎么懂这里的this,特别是上面的Class的定义,不明白为什么要这样做…能不能帮我解释一下这段代码?
var Class = {
create: function(){
return function(){this.initialize.apply(this,arguments);}
}
}var Drag = Class.create();
Drag.prototype={
initialize:function(arg1,arg2){
//函数体省略
}
}我还是不怎么懂这里的this,特别是上面的Class的定义,不明白为什么要这样做…能不能帮我解释一下这段代码?
this只是这个匿名函数函数实体的指针.
apply(this,arguments)
是为了将这个this指针替代运行initialize函数时对initialize的指针.也就是他实际要做的是.
var Drag = function(){this.initialize.apply(this,arguments);}
然后因为Drag的原型被修改成
Drag.prototype={
initialize:function(arg1,arg2){
//函数体省略
}
}
所以如果他生成一个新的Drag实例的话.
var a = new Drag();
就会运行Drag.initialize(),并且运行时,initialize中你省略的函数体中的this都会指向new的Drag实体.
Sample = function(){
this.text = 'hello';
}
var s = new Sample();//这个时候上面的this指向的就是s
alert(s.text);//显示的是hello
//函数体省略
}
Drag.prototype={
} 其实就是这样
那样是好看而已
悟透javascript
http://www.cnblogs.com/leadzen/archive/2008/02/25/1073404.html