您的位置:首页 > Web前端 > JavaScript

JavaScript中,关于new的那些事

2014-12-28 12:33 316 查看
这篇文章是自己对new学习过程中的一些理解,有不对的地方希望指出,接受组织的批评教育。

导火线,前段时间学习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实例方法跟属性的问题了,具体我就不再表达自己那些浅显的见解,有高手已经解答
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: