JavaScript中,关于new的那些事
2014-12-28 12:33
316 查看
这篇文章是自己对new学习过程中的一些理解,有不对的地方希望指出,接受组织的批评教育。
导火线,前段时间学习jQuery的时候,看到源码中有这样一段:
短时间内,对于我这种初学者来说,感觉信息量有点大。第一,jQuery.fn是什么东西;第二,new加上后面那一大串返回什么;第三,看上是jQuery的构造函数,为什么要这么折腾。
好,经过一段时间的研究,慢慢来解答。
首先,jQuery.fn就是jQuery.prototype,相当于给jQuery原型弄了个马甲,看起来短一些。
其次,init方法在jQuery的原型中有定义,大概做的几件事就是:
把selector与context传给jQuery选择器引擎Sizzle建立元素列表
返回jQuery实例对象
好,也就是说,不管怎么折腾,init返回的就是JQuery实例对象。接下来看一下某大神对new的一个说明:
只要new表达式之后的constructor返回(return)一个引用对象(数组,对象,函数等),都将覆盖new创建的匿名对象;如果返回(return)一个原始类型(无return时其实为return原始类型undefined),那么就返回new创建的匿名对象。
有了这段解答,那么,姑且猜测
接下来验证一下,先来代码:
可以看到运行结果与描述一致,demo1-3都被构造函数的返回值覆盖了,demo4返回了一个原始类型,因此new操作之后返回的就是demo4匿名对象。要提一下的是,原始类型指的是String,Boolean,Number,Undefined,Null这5类。测试代码就不贴出来了。
好了,这下new在背后干的勾当已经基本弄清了,但是jQuery中还有一段定义
导火线,前段时间学习jQuery的时候,看到源码中有这样一段:
jQuery = function(selector, context) { return new jQuery.fn.init(selector, context); }
短时间内,对于我这种初学者来说,感觉信息量有点大。第一,jQuery.fn是什么东西;第二,new加上后面那一大串返回什么;第三,看上是jQuery的构造函数,为什么要这么折腾。
好,经过一段时间的研究,慢慢来解答。
首先,jQuery.fn就是jQuery.prototype,相当于给jQuery原型弄了个马甲,看起来短一些。
其次,init方法在jQuery的原型中有定义,大概做的几件事就是:
把selector与context传给jQuery选择器引擎Sizzle建立元素列表
返回jQuery实例对象
好,也就是说,不管怎么折腾,init返回的就是JQuery实例对象。接下来看一下某大神对new的一个说明:
只要new表达式之后的constructor返回(return)一个引用对象(数组,对象,函数等),都将覆盖new创建的匿名对象;如果返回(return)一个原始类型(无return时其实为return原始类型undefined),那么就返回new创建的匿名对象。
有了这段解答,那么,姑且猜测
new jQuery.fn.init(selector, context)返回的就是jQuery对象。
接下来验证一下,先来代码:
function demo1 () { return { name: "Ichigo", firstName: "Kurosaki" } } function demo2 () { return ["bleach"]; } function demo3 () { return function () { var str = "doNothing"; } } function demo4 () { this.name = "Bruce"; this.firstName = "Wayen"; return this.name + " " + this.firstName; } console.log(new demo1()); // Object {name: "Ichigo", firstName: "Kurosaki"} console.log(new demo2()); // ["bleach"] console.log(new demo3()); // function () {var str = "doNothing";} console.log(new demo4()); // demo4 {name: "Bruce", firstName: "Wayen"}
可以看到运行结果与描述一致,demo1-3都被构造函数的返回值覆盖了,demo4返回了一个原始类型,因此new操作之后返回的就是demo4匿名对象。要提一下的是,原始类型指的是String,Boolean,Number,Undefined,Null这5类。测试代码就不贴出来了。
好了,这下new在背后干的勾当已经基本弄清了,但是jQuery中还有一段定义
init.prototype = jQuery.fn这就关系到jQuery实例方法跟属性的问题了,具体我就不再表达自己那些浅显的见解,有高手已经解答
相关文章推荐
- JavaScript关于数字的那些事
- 关于javascript的new做些什么(待翻译)
- 关于javascript, 在 new ActiveXObject("MSXML")时错误 解决办法
- javascript中 关于eval的那些事
- javascript 关于new()继承的笔记
- 关于JavaScript的那些话
- 关于JavaScript的那些话
- 关于javascript function对象那些迷惑
- JavaScript中,关于new的那些事
- 关于javascript new 实例化和 prototype new 实例化的区别
- javaScript-关于new的笔记
- 关于javascript function对象那些迷惑分析
- 关于javascript removeChild的那些事
- 关于JavaScript中的new和原型的相关知识总结
- 关于javascript function对象那些迷惑分析
- 关于Javascript内存泄露的那些小事儿
- 关于Javascript回调函数的那些事
- 关于JavaScript的那些话
- 关于用户自定义控件与引用该控件的页面之间的javascript脚本冲突
- 关于HTML元素的Table控件javascript添加删除表中行列的方法!