解决方案 »
- dtree如何点击父节点标题内容,展开子节点内容
- jquery 视频播放器插件
- 关于如何复制数组
- 散分,祝大家元旦快乐!
- ………………………………………………………………………………迷惑了几个月~ 大家也看看这句有什么用???
- 正则,提取<# #>标签中间的内容,在线等
- 一个简单语句,IE可以,FF不行,请教。
- 一个正则表达式的问题,一段字符串要同时满足 第一个字为“你”,中间含有一个字“真帅”,字符串长度为9,可以是字符和数字的组合
- 我需要从数据库中SELECT出记录,显示在<TEXTAREA>中,然后把这个 <TEXTAREA>设成只读的,怎么办
- 是我的问题太难了,还是这里的高手比较少啊?
- 原型被重置后的构造函数问题
- 如何用原生js实现展开收起box的功能?
如果 把 var aa = new a("sd"); 改为 a("sd");
那可以肯定的是 this==window 这个不用怀疑吧 因为a 有全局对象window来调用 谁调用this指向谁 create的 this==obj也不用说了
而 new function 的作用是 引用下专业语言
A new object is created, inheriting from foo.prototype.
The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
差不多的意思是
1 创建一个新的对象,并让 this 指针指向它
2 将函数的 prototype 对象的所有成员都赋给这个新对象
3 执行函数体 对这个对象进行初始化操作
4 返回1中创建的对象
所以这里的this指的是a的一个对象 这是javascript规定的对象 有自己的方法 可以log出来看看
不等于任何一个其他对象哦
create : function(){
return function(){//这个函数会由全局调用(区分清楚,这个不是create方法,外面一层函数才是),这个函数会中this指代window
console.log(this == Object)
console.log(this == obj)
console.log(this == a)
this.initialize.apply(this,arguments);
}
}
}
var a = obj.create();
a.prototype = {
initialize :function(v) {//这个函数是a的方法,如果用a构造对象,里面this指代该对象
this.name = v;
},
bb : function(){//同上
return this.name;
}
}
var aa = new a("sd");
alert(aa.bb())//bb方法返回的肯定是aa.name属性this指代的是方法的拥有者,记住这一条就会明白函数被掉用时this的指代了
这句就简单了
这个对象从prototype里继承了 initialize 方法 当然还有 下面的bb方法
简单的理解就是 调用 initialize
然后保存 this指针 让window 插不进来 呵呵
apply方法就不说了 我是2把子 教不来人
alert(this+'\n'+(this==window));
};
t();
t.apply(t,[]);
var o={k:'123'};
var t=function (){
alert(this.k+'\n'+(this==window));
};
t();
t.apply(o,[]);
this.initialize.apply(this,arguments)
这一句你也可以改为this.initialize(arguments[0]);或this.initialize.call(this,arguments[0]);
但明显没有原代码好,没原代码通用。
var a = return function(){
console.log(this == Object);
//console.log(this == obj)
console.log(this == a);
this.initialize.apply(this,arguments);
}
a.prototype = {
initialize :function(v) {
this.name = v;
},
bb : function(){
return this.name;
}
}
var aa = new a("sd");
alert(aa.bb())
不就相当于
var a = function(){this.initialize.apply(this,arguments);}
么,那么这个this肯定就是指向a函数的实例化对象。也就是aa
然后回过头来看 10楼 ywtywt337 的回复 已经点的很简单明了了
var a = function(){
this.initialize.apply(this,arguments);
};
a.prototype = {
initialize :function(v) {
this.name = v;
},
bb : function(){
return this.name;
}
}
如果要在构造函数里调用原型链的方法并且传递参数应该只有这样写吧?this.initialize.apply(this,arguments);
这样this的指向就明白了。
为此我写了:
var b = {};
b.init = function () {return 1};alert (b.init.apply(this));
alert (b.init.apply(b));//
alert (b.init());
更明白点!不知道我这样理解行不行。高手指正下!