export function add(a, b) {
return a + b;
}
export const PI = 3.14;
2. 在需要引用模块的地方,使用import关键字来引入模块。
import { add, PI } from './math.js';
console.log(add(1, 2)); // 输出3
console.log(PI); // 输出3.14
模块继承的优势在于可以按需导入需要的函数或变量,减少了代码的冗余。
相比之下,原型继承是一种通过对象的原型链来实现继承的方式。
原型继承的使用方法如下:
1. 创建一个父对象,可以是一个普通对象或者是一个函数。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
}
const parent = new Parent();
parent.sayHello(); // 输出 Hello, parent
2. 创建一个子对象,通过将父对象赋值给子对象的原型来实现继承。
function Child() {
this.name = 'child';
}
Child.prototype = Object.create(Parent.prototype);
const child = new Child();
child.sayHello(); // 输出 Hello, child
原型继承的优势在于可以实现对象的继承和方法的共享。
总结:
ES6中的模块继承是一种简洁、直观的继承方式,通过export和import语句来实现。
原型继承是一种通过对象的原型链来实现继承的方式,可以实现对象的继承和方法的共享。
希望通过本文的讲解,你能更好地理解ES6中的模块继承和原型继承的工作原理及其区别。本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com
