Person.prototype.greet = function () { // 设置原型上的方法 console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); };
// 使用 new 创建实例 const alice = newPerson('Alice', 25); // 创建了一个新的对象 {...} // alice.__proto__ -> Person.prototype console.log(alice.name); // 输出 'Alice' console.log(alice.age); // 输出 25 alice.greet(); // 输出 'Hello, my name is Alice and I am 25 years old.'
注意:只要构造函数含有this,避免忘记使用 new 调用构造函数,否则 this 会指向全局对象(严格模式下为 undefined)