JavaScript-条件扩展 [英] JavaScript - Class extend on condition

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

问题描述

这是东西.我有一个叫做A的主要班级. 我希望该类扩展B类.

Here is the thing. I have a main class called A. I want this class to extend class B.

class A extends B {}

但是实际上,我希望B类在特定条件下扩展C,D或E:

But in fact, I want the class B to extend C, D or E on a specific condition:

class B extends B1 {}

class B extends B2 {}

class B extends B3 {}

因此B类将是伪"类,仅用于检查条件,然后扩展正确的类. 最终,结果将与以下内容相同:

So the B class would be a "fake" class, just to check a condition and then extend the right class. In the final, the result would be the same as:

class A extends B1 {}

class A extends B2 {}

class A extends B3 {}

我知道这在PHP中是可能的,例如抽象类或包装器类. 但是如何在JavaScript ES6中做到这一点?

I know this is possible in PHP, with abstract classes or wrapper classes for example. But how to do that in JavaScript ES6?

谢谢

推荐答案

因此javascript中的类实际上不是按照与其他语言相同的经典继承方式来设置的,最好的方法是设置Java语言的原型.您正在处理的对象.有几种方法.

So classes in javascript are really not setup in the same classical inheritance way as other languages, the best way to do what you want is to set the prototype of the object you are dealing with. There are a few ways.

Object.setPrototypeOf(currentObj, newPrototype);

newPrototype是要从中继承的对象.如果您想了解其内部工作原理,那么这里有几篇很好的文章.

Where newPrototype is the object you are wanting to inherit from. Here are a couple good articles on it if you want to learn the inner workings.

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md

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

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