new 操做符内部实现原理是什么?前端
new
操做符常常被用到,用面向对象语言们通用的观点来看:new
是用来实例化一个类,从而在内存中分配一个实例对象。面试
new
关键字会进行以下操做:bash
JavaScript
对象(即{}
);prototype
赋值给对象的 __proto__
属性 ;this
上下文 ;示例:函数
function Person(name) {
this.name = name;
}
function Person2(name) {
this.name = name;
return this.name;
}
function Person3(name) {
this.name = name;
return new Array();
}
function Person4(name) {
this.name = name;
return new String(name);
}
function Person5(name) {
this.name = name;
return function() {};
}
var person = new Person('John'); // {name: 'John'}
var person2 = new Person2('John'); // {name: 'John'}
var person3 = new Person3('John'); // []
var person4 = new Person4('John'); // 'John'
var person5 = new Person5('John'); // function() {}
复制代码
Person
自己是一个普通函数,当经过new
来建立对象时,Person
就是构造函数了。ui
JS引擎执行这句代码时,在内部作了不少工做,用伪代码模拟其工做流程以下:this
new Person("John") = {
var obj = {};
obj.__proto__ = Person.prototype; // 此时便创建了obj对象的原型链: obj->Person.prototype->Object.prototype->null
var result = Person.call(obj,"John"); // 至关于obj.Person("John")
return typeof result === 'object' ? result : obj; // 若是无返回值或者返回一个非对象值,则将obj返回做为新对象
}
复制代码
原型链是面试中必考题目,new
和原型链常常一块儿出现,看下面这道题目:spa
function Parent(name) {
this.name = name;
}
var child = new Parent('前端名狮');
console.log(Parent.prototype); // {constructor: function Parent(name){this.name = name}}
console.log(child.prototype); // undefined
复制代码
JavaScript 中,万物皆对象!但对象也是有区别的。分为普通对象和函数对象,Object ,Function 是JS自带的函数对象。 函数对象会预约义一个属性就是原型对象prototype
。注:普通对象没有prototype
,但有__proto__
属性。prototype
Parent
是函数对象,Parent.prototype
是存在的。code
由上面的new
操做符的工做原理,咱们知道它返回的是一个普通对象{}
,因此它是没有prototype
属性的,输出undefined
cdn
扫一扫 关注个人公众号【前端名狮】,更多精彩内容陪伴你!