要设置构造函数的原型,可以使用以下方法:
function Person(name, age) {
this.name = name;
this.age = age;
}
const personPrototype = {
introduce() {
console.log(`My name is ${this.name} and I am ${this.age} years old.`);
}
};
const newPrototype = Object.create(personPrototype);
Person.prototype = newPrototype;
const person = new Person("John", 25);
person.introduce(); // My name is John and I am 25 years old.
function Person(name, age) {
this.name = name;
this.age = age;
}
const personPrototype = {
introduce() {
console.log(`My name is ${this.name} and I am ${this.age} years old.`);
}
};
function createObject(prototype) {
function F() {}
F.prototype = prototype;
return new F();
}
const newPerson = createObject(personPrototype);
const person = newPerson.constructor("John", 25);
person.introduce(); // My name is John and I am 25 years old.
这些方法是在不使用Object.setPrototypeOf()的情况下设置构造函数的原型的替代方法。