new的过程
Posted 纸 飞机
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了new的过程相关的知识,希望对你有一定的参考价值。
函数调用时前面不加new就按普通函数来 执行。加new后对其进行了相应的变动, 按构造函数来执行。
new的具体过程如下:
//例子:
function Person(name,age) {
this.userName = name;
this.userAge = age;
}
var personl = new Person('LULU',20)
1、创建一个新的空对象。(即实例对象)
obj = {}
2 、设 置 原 型 链
将新对象obj的 __proto__属性指向构造函数的prototype 对象。(即所有实例对象通过__proto__可 以访问原型对象。构造函数的原型被其所有实例对象共享。)
obj.__proto__= Person.prototype
3 、将构造函数的thi s改指向新对象ob j并 执行函数代码。
(即给实例对象设置属性 userName, userAge并赋值。)
var result = Person.apply(obj,['LULU',20])
4 、如果构造函数中没有人为返回一个对象 类型的值,则返回这个新对象obj。否则直 接返回那个对象类型值。(一般定义的构造 函数中不写返回值。)
if (typeof(result) == 'object') {
return result;
}else{
return obj;
}
手动实现一个new操作,参数为构造函数 及其传参
//构造函数
function Person(name,age) {
this.userName = name;
this.userAge = age;
}
Person.prototype.sayAge = function(){
console.Iog(this.userAge)
}
// new操作函数newFun
function newFun() {
var obj = {};
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
var ret = Constructor.apply(obj, arguments);
return typeof ret === 'object' ? ret: obj;
};
//调用 newFun
var s1 = newFun(Person, 'xiaoyun',20);
console.log(s1.userName) //xiaoyun
console.log(s1.sayAge()) //20
备注:[].shift.call(arguments):删除并返回参数列表arguments中第一个参数,即获得构造函数。arguments剩余参数为构数传参。arguments是类数组,没有数组方法shift,可更改shift方法的this指向从而运用到 arguments 上。
以上是关于new的过程的主要内容,如果未能解决你的问题,请参考以下文章