new方法模拟
function Person(name, arg) {
this.name = name
this.arg = arg
}
Person.prototype.setName = function () {
console.log('this.name:', this.name)
}
const Man = new Person('zhangsan', 27);
Man.setName()
new操作符会处理下面四件事:
1.创建一个空的js对象;
2.链接这个新对象到另一个指定的对象
3.将this指向创建的这个空对象
4.如果该函数没有返回对象,则返回this。
function newFunc() {
// 创建一个新对象
// 不能这样创建 Object.create(null) 没办法获取原型链上的函数方法
let result = {};
// 将第一个参数作为构造函数链接到新对象上
const construct = Array.prototype.shift.call(arguments);
// 链接新对象到另一个对象
result.__proto__ = construct.prototype;
// 取得构造函数的返回值
var conRes = construct.apply(result, arguments);
// 判断返回类型
return conRes instanceof Object ? conRes : result;
}
const man = newFunc(Person, 'zhangs', 27)
console.log(man.__proto__ === Person.prototype)
man.sayName()

浙公网安备 33010602011771号