new
new 操作一个构造函数或类来获取实例
// ES5中的构造函数
function Person(name, age){
this.name = name;
this.age = age
}
Person.prototype.sayAge = function(){
console.log(`${this.name} is ${this.age} years old`)
}
var lucy = new Person("Lucy", 18)
lucy.sayAge() // Lucy is 18 years old
// ES6中的class
class Person{
constructor(name,age){
this.name = name;
this.age = age
}
sayAge(){
console.log(`${this.name} is ${this.age} years old`)
}
}
var lucy = new Person("Lucy", 18) // Lucy is 18 years old
lucy.sayAge()
new操作中做了什么
-
以构造器的prototype为原型,创建新对象;
-
将this(也就是上一步创建出的新对象)和调用参数传给构造器,执行;
-
如果构造器没有手动返回对象,则返回第一步创建的新对象,如果有,则舍弃掉第一步创建的新对象,返回手动return的对象
new过程中会新建对象,此对象会继承构造器的原型与原型上的属性,最后它会被作为实例返回这样一个过程
手写一个new方法
let newMethod = function(Parent, ...rest){
// 1、以构造器的prototype属性为原型,创建新对象
let child = Object.create(Parent.prototype)
// 2、将this(也就是上一句中的新对象)和调用参数传给构造器,执行
let result = Parent.call(child, ...rest)
// 3、如果构造器没有手动返回对象,则返回第一步创建的新对象,如果有,则舍弃掉第一步创建的新对象,返回手动return的对象
return result instanceof Object ? result : child
}
let Parent = function (name, age) {
this.name = name;
this.age = age;
};
测试使用
let Parent = function (name, age) {
this.name = name;
this.age = age;
};
Parent.prototype.sayName = function () {
console.log(this.name);
};
const child = newMethod(Parent, 'Kitty', 100);
child.sayName() // Kitty