// 定义一个构造函数 function Animal(name) { this.name = name; }
// 在 Animal 的原型上添加方法 Animal.prototype.speak = function() { console.log(this.name + ' 发出声音'); };
// 定义一个新的构造函数 Dog,继承自 Animal function Dog(name) { Animal.call(this, name); // 继承属性 }
// 设置 Dog 的原型为 Animal 的实例,建立原型链 Dog.prototype = new Animal(); Dog.prototype.constructor = Dog;
// 在 Dog 的原型上添加特定方法 Dog.prototype.bark = function() { console.log(this.name + ' 汪汪叫'); };
// 创建一个 Dog 实例 const myDog = new Dog('旺财');
// 调用继承自 Animal 的方法 myDog.speak(); // 输出: 旺财 发出声音
// 调用 Dog 自身的方法 myDog.bark(); // 输出: 旺财 汪汪叫 // 定义一个原型对象 const animal = { speak() { console.log('发出声音'); } };
// 创建一个新对象,以 animal 为原型 const cat = Object.create(animal); cat.name = '咪咪';
// 调用继承自原型的方法 cat.speak(); // 输出: 发出声音 // 定义一个基类 class Animal { constructor(name) { this.name = name; }
speak() {
console.log(this.name + ' 发出声音');
}
}
// 定义一个子类,继承自 Animal class Bird extends Animal { constructor(name) { super(name); }
fly() {
console.log(this.name + ' 在飞翔');
}
}
// 创建一个 Bird 实例 const myBird = new Bird('小鸟');
// 调用继承自 Animal 的方法 myBird.speak(); // 输出: 小鸟 发出声音
// 调用 Bird 自身的方法 myBird.fly(); // 输出: 小鸟 在飞翔