new操作符的作用 创建一个构造函数的实例对象把构造函数当作普通函数执行,让方法中的this指向创造实例对象观察方法执行的返回结果:如果没有写返回值,或者返回的是原始类型的值,都以返回的实例对象为主;如果返回的是一个对象/函数,则以自己的返回为主 自己实现new操作符 function _new(Ctor, ...params) { //格式校验:能被NEW的,首先是个函数,其次需要有prototype属性,而且还不能是Symbol/BigInt构造函数... let obj, result; obj = Object.create(Ctor.prototype); result = Ctor.call(obj, ...params); if(Ctor === Number || Ctor === String || Ctor === Boolean) result = Object(result); if(result !== null /^(object|function)$/i.test(typeof result)) return result; result obj; } function Dog(name) { this.name = name; } Dog.prototype.bark = function () { console.log('wangwang'); } Dog.prototype.sayName = function () { console.log('my name is ' + this.name); } let sanmao = _new(Dog, '三毛'); sanmao.bark(); sanmao.sayName(); console.log(sanmao instanceof Dog); //=>true