JavaScript中的类继承 [英] Class Inheritance in Javascript

查看:130
本文介绍了JavaScript中的类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在JavaScript中模拟类继承。我知道类不适用于JavaScript,我们使用的方式是函数创建对象,并通过Prototype对象继承东西。

I am wondering how to simulate Class Inheritance in JavaScript. I know class doesn't apply to JavaScript, the way we use is Functions to create objects and do the inheritance things through Prototype object.

例如,如何转换这个结构转换成JavaScript:

For example, how do you convert this structure into JavaScript :

public class Mankind {
    public string name;
    public string lastname;
}

public class Person: Mankind {
    public void Run(string fromWhat) {
        //write the run logic
    }
}

这段代码在JavaScript中的效果是什么。

What is the equivalent of this piece of code in JavaScript.

编辑

我还找到了另一个链接,Douglas Crockford解释了不同的继承模型: CMS 会: JavaScript中的古典继承

I've also found another link where Douglas Crockford explains different inheritance models as CMS does: Classical Inheritance in JavaScript.

希望它也能帮助别人。

推荐答案

有很多方法可以在JavaScript中实现继承和行为重用,也许更类似于基于类的 OOP示例是伪古典继承:

There are plenty ways of implementing inheritance and behavior reuse in JavaScript, perhaps the way that is more similar to your class-based OOP example would be the pseudo-classical inheritance:

function Mankind (name, lastname) {
  this.name = name;
  this.lastname = lastname;
}

function Person (name, lastname) {
  this.name = name;
  this.lastname = lastname;

  this.run = function() {
    // run logic
  };
}
Person.prototype = new Mankind();
Person.prototype.walk = function () {
  // walk logic
};

运行 walk 是第一个将存在于 Person 的每个对象实例上,第二个方法 walk 将仅存在于 Person.prototype 中,并且将通过原型链访问。

The difference between run and walk is that the first will exist on every object instance of Person, and the second method, walk, will exist only in Person.prototype and will be accessed through the prototype chain.

在这个模式中,你看到一些代码重复,我们需要逻辑来初始化继承的构造函数中的字段,避免这种情况的另一个模式是构造函数应用程序:

In this pattern you see a bit of code duplication, we need the logic to initialize the fields also on the inherited constructor, another pattern that avoids this, is Constructor Function application:

function Mankind (name, lastname) {
  this.name = name;
  this.lastname = lastname;
}

function Person (name, lastname) {
  Mankind.apply(this, arguments);
  this.run = function() {
    // run logic
  };
}

更多信息:

  • How to inherit from a class in JavaScript (various examples)
  • Inheritance Patterns in JavaScript (article)
  • Classical Inheritance in JavaScript (article)

这篇关于JavaScript中的类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆