new操作符做了什么?
new是什么?
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
function Person (name,age) {this.name = namethis.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出来的实例可以访问到构造函数中的属性
- new出来的实例可以访问到构造函数原型链上的方法和属性
如果在构造函数内加上返回值是什么结果呢?
-
返回基本数据类型
function Car (price) {this.price = pricereturn 20 } let bigCar = new Car(90) console.log(bigCar.price) // 90
返回基本数据类型时,返回值会被忽略
-
返回引用数据类型
function Car (price) {this.price = pricereturn { km: 200 } } let bigCar = new Car(90) console.log(bigCar.price, bigCar.km) // undefined, 200
返回引用数据类型,会被正常使用
new做了什么工作呢?
- 新建一个对象obj
- 把obj的和构造函数通过原型链连接起来
- 将构造函数的this指向obj
- 如果该函数没有返回对象,则返回this
// new操作符做了什么?function newFun(Fun, ...args) {// 1.先创建一个空对象let newObj = {};// 2. 把空对象的原型,指向构造函数的原型对象newObj.__proto__ = Fun.prototype;// 3. 把构造函数的this绑定到新的空对象身上const result = Fun.apply(newObj, args);console.log('result是:', result);// 4. 根据构造函数返回的类型判断,如果是值类型,则忽略返回值,直接返回对象;如果是引用类型,则返回这个引用类型console.log('返回的是引用类型吗?', result instanceof Object);return result instanceof Object ? result : newObj;}function Person(name) {this.name = name;// 1. 如果构造函数没有返回值,则在new的时候result是undefined,就会直接返回对象// 2. 如果构造函数的返回值是值类型,在new的时候会忽略该返回值// return 111;// return '返回值类型--字符串';// return true;// 3. 如果构造函数的返回值是引用类型,在new的时候会返回该引用类型// return { aaa: 'aaa' };}Person.prototype.say = function () {console.log('hello');};const p1 = newFun(Person, '张三');p1.say();console.log(p1)