new一个对象发生了什么?
var append = 'to me';
function sayHello(who) {
console.log(`${who} say hello, ${append}`);
var append = 'to you';
this.message = 'xxx'
}
let t = new sayHello('Mike')
console.log(t.__proto__===sayHello.prototype)
console.log(t.message)
运行结果:
Mike say hello, undefined
true
xxx
1. 像普通函数那样执行,形成私有作用域,进行形参赋值,变量提升等一系列操作
2. 默认创建一个对象,
3. 让这个对象成为当前类的实例,__proto__
指向构造函数原型
4. 让函数中的this指向这个对象
5. 代码执行
6. 默认把创建的对象返回
实现一个_new
函数,可以得到内置new一样的效果
function _new(Constructor,..args) {
//let obj = {};
//obj.__proto__ = Constructor.prototype;
let obj = Object.create(Constructor.prototype); //和上面2行等效
Constructor.call(obj,...args);
return obj;
}
let t = _new(sayHello,'Mike')
console.log(t.__proto__===sayHello.prototype)
console.log(t.message)
Mike say hello, undefined
true
xxx