javascript 具有与大多数传统 oop 语言不同的继承机制。原型是主要焦点,而 es6 类提供了更现代的方法。让我们看看 es6 类如何提高可读性和实用性以及原型继承如何运作。
javascript 中的每个对象都有一个到另一个对象的内部链接,称为其原型。这个原型对象可以有自己的原型,形成一条链。
示例:
const animal = { eats: true }; const rabbit = object.create(animal); rabbit.hops = true; console.log(rabbit.eats); // true (inherited) console.log(rabbit.hops); // true (own property)
说明:
在这里,兔子继承了动物的饮食习惯。这演示了对象如何通过继承共享属性。
在 es6 类之前,javascript 使用构造函数来创建对象并初始化其属性。
示例:
function animal(name) { this.name = name; } animal.prototype.eats = true; const dog = new animal('dog'); console.log(dog.name); // dog console.log(dog.eats); // true
说明:
animal 构造函数初始化 name。 eats 属性是通过 animal.prototype 添加的,从而实现继承。
主对象充当其他对象的原型。
示例:
const masterobject = { type: 'generic' }; const specificobject = object.create(masterobject); specificobject.name = 'specific'; console.log(specificobject.type); // generic (inherited) console.log(specificobject.name); // specific (own property)
说明:
masterobject 是共同祖先,specicobject 继承了它的 type 属性,同时添加了 name。
javascript 查找原型链以查找属性和方法。
示例:
const grandparent = { role: 'grandparent' }; const parent = object.create(grandparent); parent.role = 'parent'; const child = object.create(parent); console.log(child.role); // parent
说明:
子对象寻找角色。它找到父级的角色,演示原型链如何解析属性查找。
对象可以通过原型继承来共享方法。
示例:
function animal(name) { this.name = name; } animal.prototype.speak = function() { console.log(this.name + ' makes a noise.'); }; function dog(name) { animal.call(this, name); } dog.prototype = object.create(animal.prototype); dog.prototype.constructor = dog; dog.prototype.bark = function() { console.log(this.name + ' barks.'); }; const dog = new dog('rex'); dog.speak(); // rex makes a noise. dog.bark(); // rex barks.
说明:
dog 继承自 animal,允许它访问语音。它还定义了自己的 bark 方法。
es6 引入了一种更干净、更直观的方式来创建类。
示例:
class animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } }
说明:
这种基于类的语法简化了对象的创建和继承,使代码更具可读性。
es6 允许定义动态访问或修改对象属性的方法。
示例:
class rectangle { constructor(width, height) { this.width = width; this.height = height; } get area() { return this.width * this.height; } set area(value) { this.width = math.sqrt(value); this.height = math.sqrt(value); } } const rect = new rectangle(10, 20); console.log(rect.area); // 200 rect.area = 100; console.log(rect.width); // 10 console.log(rect.height); // 10
说明:
area 是一个使用 getter 和 setter 的计算属性,允许动态更新。
静态方法属于类本身,而不属于实例。
示例:
class mathhelper { static add(a, b) { return a + b; } } console.log(mathhelper.add(2, 3)); // 5
说明:
add 是一个可以直接在 mathhelper 上访问的静态方法,对于实用函数很有用。
多态允许子类重新定义父类的方法。
示例:
class Animal { speak() { console.log('Animal makes a noise.'); } } class Dog extends Animal { speak() { console.log('Dog barks.'); } } const myPet = new Dog(); myPet.speak(); // Dog barks.
说明:
dog 覆盖 animal 的发言,提供自己的实现。
javascript 面向对象编程的基础由 es6 类和原型继承组成。通过了解如何使用构造函数、原型和 es6 类,可以改进编写可重用、可维护的代码。要充分利用 javascript 的继承范例,请接受这些想法!
关注我:github linkedin