function Person(name) {
this.name = name
}
Person.prototype.sayHi = function() {
console.log('hi,', this.name)
}
let p = new Person('rory');
p.sayHi(); // hi, rory
console.log(p.__proto__ === Person.prototype); // true
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log('hi,', this.name)
}
}
let p = new Person('rory');
p.sayHi(); // hi, rory
console.log(p.__proto__ === Person.prototype); // true
function myNew(constructor, ...args) {
// 1.声明一个实例对象
let obj = {};
// 2.将实例对象的原型指向构造函数的原型对象
Object.setPrototypeOf(obj, constructor.prototype)
// 3.将构造函数的this指向此实例对象
const result = constructor.call(obj, ...args)
// 4.返回此实例对象
return typeof result === 'object' ? result : obj
}
function Person() {
this.name = 'yuyy'
}
const p = new Person();
console.log(p); // Person { name: 'yuyy' }
function Person1() {
this.name = 'yuyy'
return { age: 18 }
}
const p1 = new Person1();
console.log(p1); // { age: 18 }
function Person2() {
this.name = 'yuyy'
return 1
}
const p2 = new Person2();
console.log(p2); // Person2 { name: 'yuyy' }
function Foo() {
console.log(new.target?.name);
}
Foo();
new Foo();