Prototype原型
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.sayHello = function() { console.log(`Hello, I am ${this.name}.`); }; const person1 = new Person('Alice', 30); const person2 = new Person('Bob', 25); person1.sayHello(); // Hello, I am Alice. person2.sayHello(); // Hello, I am Bob.
function Animal() { this.isAlive = true; } Animal.prototype.move = function() { console.log('Moving...'); }; function Dog() { this.breed = 'Golden Retriever'; } Dog.prototype = new Animal(); Dog.prototype.bark = function() { console.log('Woof!'); }; const myDog = new Dog(); console.log(myDog.isAlive); // true myDog.move(); // Moving... myDog.bark(); // Woof!
Last updated