前言
本系列主要整理前端面试中需要掌握的知识点。本节介绍JS中new关键字的具体操作以及为什么手写new的最后一步要判断返回值类型。
一、new是什么
- new操作符用于创建一个给定构造函数的实例对象。如
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
console.log(this.name)
}
const person1 = new Person('Tom', 20)
console.log(person1) // Person {name: "Tom", age: 20}
t.sayName() // 'Tom'
- new 通过构造函数 Person 创建出来的实例可以访问到构造函数中的属性;
- new 通过构造函数 Person 创建出来的实例可以访问到构造函数原型链中的属性;
- 构造函数如果返回基本数据类型,那么这个返回值并没有作用,如果返回的是一个对象,那个这个返回值会被正常使用。
function Test(name) {
this.name = name
console.log(this) // Test { name: 'xxx' }
return { age: 26 }
}
const t = new Test('xxx')
console.log(t) // { age: 26 }
console.log(t.name) // 'undefined'
二、new创建实例的流程
- 创建一个新的对象obj;
- 将对象与构建函数通过原型链接连接起来;
- 将构造函数中this绑定到新建的对象obj上;
- 根据构建函数返回类型作为判断,如果是原始值则被忽略,如果是返回对象,则需要正常处理。
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
}
const person1 = new Person('Tom',20)
console.log(person1);
person1.sayName();
以上代码的创建流程为:
三、手写实现new操作符
function mynew(Func,...args){
const obj = {}; // 1.创建一个新对象
obj.__proto__ = Func.prototype; // 2.新对象原型指向构造函数原型对象
let result = Func.apply(obj,args) // 3.将构建函数的this指向新对象
return result instanceof Object ? result : obj // 4.根据返回值判断
}
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
}
const person1 = mynew(Person,"fanafan",18)
console.log(person1);
person1.sayName();
四、为什么手写new的最后一步要判断返回值类型?
在new中,有这样一种特性: 构造函数如果返回基本数据类型,那么这个返回值并没有作用,如果返回的是一个对象,那个这个返回值会被正常使用。
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
console.log(this.name)
}
const person = new Person('Tom', 20)
console.log(person) // Person {name: "Tom", age: 20}
function Person2(name, age){
this.name = name;
this.age = age;
return {'sex':'女'}
}
const person2 = new Person2('Tom', 20)
console.log(person2) // {'sex':'女'}
在new的手写代码中解释就是:
版权声明:本文为weixin_44337386原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。