在JavaScript中,继承模式是一种用于实现对象之间共享属性和方法的机制,JavaScript 提供了几种不同的继承方式,包括原型链继承、构造函数继承、组合继承和寄生组合继承等。
以下是摘自《JavaScript: The Good Parts》中的关于“Functional Inheritance”模式的描述:
Functional Inheritance
Functional inheritance is a pattern that uses functions to achieve inheritance. It's not a common pattern in JavaScript, but it can be useful in certain situations. Here's how it works:
1、Define a function that creates an object with the desired properties and methods.
2、Create another function that extends the first function by adding more properties and methods.
3、Use the second function to create objects that have both sets of properties and methods.
Here's an example:
// Base "class" function mammal(name) { return { name: name, speak: function() { console.log(this.name + ' makes a noise.'); } }; } // Derived "class" function cat(name) { var that = mammal(name); // Create a base object that.speak = function() { // Override the speak method console.log(this.name + ' says Meow!'); }; return that; } // Another derived "class" function dog(name) { var that = mammal(name); // Create a base object that.speak = function() { // Override the speak method console.log(this.name + ' says Woof!'); }; return that; } // Create instances var myCat = cat('Whiskers'); var myDog = dog('Rover'); myCat.speak(); // Whiskers says Meow! myDog.speak(); // Rover says Woof!
In this example:
mammal
is a function that creates an object with aname
property and aspeak
method.
cat
anddog
are functions that extend themammal
function by overriding thespeak
method.
Instances ofcat
anddog
are created using these functions, and they inherit properties and methods from themammal
function.
This pattern is less commonly used in modern JavaScript development because it doesn't leverage the built-in prototype chain for inheritance, which can be more efficient and easier to understand. However, it can still be useful in certain scenarios where you need a lightweight or functional approach to inheritance.