【问题标题】:What is the "extends" keyword in Spider?Spider中的“extends”关键字是什么?
【发布时间】:2023-03-23 03:55:01
【问题描述】:

Spider 通过添加 2 个关键字来包含 JavaScript 原型 OOP:extendssuper

  • 它们是什么?
  • 他们解决了什么问题?
  • 什么时候合适,什么时候不合适?

【问题讨论】:

标签: javascript oop prototype keyword spiderlang


【解决方案1】:

extends 关键字允许您继承现有对象。例如,假设您有一个 Animal 对象:

fn Animal(name) {
  this.name = name;

  this.walk = fn() {
    console.log('\(name) is walking...');
  };
}

Animal.prototype.getLegs = fn() {
  return 4;
};

您现在可以使用 extends 关键字创建另一个继承 Animal 的对象:

fn Spider(name)
  extends Animal(name) {

}

Spider.prototype.getLegs = fn() {
  return 8;
};

当您创建一个新的Spider 对象时,您将自动拥有您的walk 方法,因为Spider 扩展了Animal

var spider = new Spider("Skitter the Spider");
spider.walk();

Spider(语言)还提供了super 关键字,可以让您轻松访问您正在扩展的对象。例如:

Spider.prototype.getLegs = fn() {
  return super.getLegs() + 4; 
};

spider.getLegs(); // => 8

实施

Spider 中的这段代码:

fn Spider() extends Animal {}

编译为以下 JavaScript:

function Spider() {
  Animal.call(this);
}

Spider.prototype = Object.create(Animal);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多