new是什么?
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
function Person (name,age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function () {
console.log(this.name)
}
let man = new Person('xl',20)
console.log(man) // Person { name: 'xl', age: 20 }
man.sayName() // 'xl'
- new通过Person创建出来的实例可以访问到构造函数中的属性
- new通过Person创建出来的实例可以访问到构造函数原型链上的方法和属性 如果在构造函数内加上返回值是什么结果呢?
- 返回基本数据类型
function Car (price) {
this.price = price
return 20
}
let bigCar = new Car(90)
console.log(bigCar.price) // 90
可以看到返回基本数据类型时返回值会被忽略
- 返回引用数据类型
function Car (price) {
this.price = price
return { km: 200 }
}
let bigCar = new Car(90)
console.log(bigCar.price, bigCar.km) // undefined, 200
可以看到返回引用数据类型会被正常使用
new的流程
new做了什么工作呢?
- 新建一个对象
obj - 把obj的和构造函数通过原型链连接起来
- 将构造函数的
this指向obj - 如果该函数没有返回对象,则返回
this
实现一个new
function myNew (func, ...args) {
const obj = Object.create(func.prototype) // Object.create() 方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
let result = func.apply(obj, args)
return result instanceof Object ? result : obj
}
let p = myNew(Person, "huihui", 123)
console.log(p) // Person {name: "huihui", age: 123}
p.sayName() // huihui