做了什么?
1、创建了一个空的js对象(即{})
2、将空对象的原型prototype指向构造函数的原型
3、将空对象作为构造函数的上下文(改变this指向)
4、对构造函数有返回值的判断
结论:
在new的时候,会对构造函数的返回值做一些判断:
1、如果返回值是基础数据类型,则忽略返回值;
2、如果返回值是引用数据类型,则使用return 的返回,也就是new操作符无效;
function Person1(num) {
this.num = num
this.say = function () {
console.log('person1 ', num)
}
}
let a1 = new Person1('a1')
let a2 = new Person1('a2')
a1.say()
a2.say()
function Person2(num) {
let obj = new Object()
obj.num = num
obj.say = function () {
console.log('person2 ', num)
}
return obj
}
// let b2 = new Person2('b2')
// b2.say()
// let b3 = new Person2('b3')
// b3.say()
let b4 = Person2('b4')
b4.say()
let b5 = Person2('b5')
b5.say()
打印结果
person1 a1
person1 a2
person2 b4
person2 b5