试图理解JavaScript的继承性 [英] Trying to understand JavaScript inheritence

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

问题描述

我是JavaScript的新手,来自C ++ / Java背景,因此我更习惯于'经典'语言。

I am very new to JavaScript and am coming from a C++/Java background, so I am more used to 'classical' languages.

我将如何实现跟在JavaScript中,因为它没有类!?

How would I implement the following in JavaScript as it doesn't have classes!?

假设我有一个基类A,它定义了派生类B和C应该实现的一些函数,例如( Java ish psuedo-code):

Suppose I have a base class A which defines some functions that derived classes B and C should implement, for example (Java ish psuedo-code):

public class A {
  public void doSomething();
  public void doSomethingElse();
};

public class B extends A {
  public void doSomething() { 
    // does B sort of something 
  };

  public void doSomethingElse() { 
    // does B sort of something else };
  };
};

public class C extends A {
  public void doSomething() { 
    // does C sort of something 
  };

  public void doSomethingElse() { 
    // does C sort of something else };
  };
};

我想创建一个B或C并使用它,因为它知道它将具有A中定义的所有函数。

I then want to create a B or an C and work with it, knowing that it will have the all the functions defined in A.

例如

A a = new B();
b.doSomething();

我甚至不知道在JS编程时这是不是我应该怎么想?我已经阅读了一些道格拉斯Crockfords网页,但我仍然感到困惑!!!。

I don't even know if this is how I should be thinking when programming in JS? I have read some of Douglas Crockfords web pages, but I am still confused!!!.

推荐答案

function A() {

};

A.prototype.doSomething = function() {
    console.log("hi")
}

A.prototype.doSomethingElse = function() {}

function B() { 
   A.apply(this,arguments) ) 
};

function C() { 
   A.apply(this,arguments) ) 
};

B.prototype = Object.create(A.prototype);
C.prototype = Object.create(A.prototype);

var b = new B();
var c = new C();

b.doSomething();
c.doSomethingElse();

您可以通过在函数的原型链上设置这些对象来继承其他对象。

You can inherit from other objects by setting those objects on the prototype chain of the function.

由于您可能想要覆盖这些基本功能,您可以这样做

Since you may want to override these base functions you can then do that like this

B.prototype.doSomething = function() {
   console.log("goodbye");
}

当你调用doSomething时,b类型的对象会说再见而不是你好c将保持不变。

Objects of type b will then say goodbye rather than hello when you call doSomething, c will stay the same.

这是一个可以用来试验的小提琴 http://jsfiddle.net/Yp3UR/

Here's a fiddle you can play around with to experiment http://jsfiddle.net/Yp3UR/

在一些地方有很好的外部资源

There are good external resources on this in a few places

  • Mimicing classical
  • Embracing Prototypical Inheritance

在StackOverflow上你可以看看

On StackOverflow you can look at

  • What techniques can be used to define a class in JavaScript, and what are their trade-offs? for a good overview of JS classes
  • How to "properly" create a custom object in JavaScript? for a more general look at object creation in JS

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

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