什么是new
new
存在于各种语言中,作用基本大家都明白,就是通过指定类来新建一个对象。那么在JS里面,实际做的操作有哪些呢?
实际操作
可以来实现一个New
函数:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function New(func) {
var res = {};
if (func.prototype !== null) {
res.__proto__ = func.prototype;
}
var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
}
return res;
}
var obj1 = New(A, 1, 2);
// 相当于
var obj2 = new A(1,2)
具体步骤:
var res = {}
首先会创建一个空的对象res.__proto__ = func.prototype
然后对象的原型就会指向类方法的原型对象,以实现类的原型方法以及指向的原型链。var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
设定作用域为res
,然后调用func
的构造函数,传入参数为Array.prototype.slice.call(arguments, 1))
- 然后返回
ret
或者res