new命令的基本用法
new命令的作用,就是执行构造函数,返回一个实例对象。
1 2 3 4 5 6
| var Vehicle = function () { this.price = 1000; };
var v = new Vehicle(); v.price
|
new命令的原理
- 创建一个空对象,作为将要返回的对象实例。
- 将这个空对象的原型,指向构造函数的
prototype属性。
- 将这个空对象赋值给函数内部的
this关键字。
- 开始执行构造函数内部的代码。
手写new命令过程
1 2 3 4 5 6 7 8 9 10
| function mynew(Func, ...args) { const obj = {} obj.__proto__ = Func.prototype let result = Func.apply(obj, args) return result instanceof Object ? result : obj }
|
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function mynew(func, ...args) { const obj = {} obj.__proto__ = func.prototype let result = func.apply(obj, args) return result instanceof Object ? result : obj } function Person(name, age) { this.name = name; this.age = age; } Person.prototype.say = function () { console.log(this.name) }
let p = mynew(Person, "huihui", 123) console.log(p) p.say()
|