繁体   English   中英

在coffeescript继承链中注入一个新类

[英]Injecting a new class into the coffeescript inheritance chain

我有三个coffeescript类,设置如下:

class A
class C extends A
class B

这样原型链看起来像这样:

A -> C
B

我需要原型链看起来像这样:

A -> B -> C

问题在于我无法触及A和C的定义。

我想做的是创建一个可以像这样调用的注入函数:

inject B, C

在A之前将B注入C的原型链中,然后将B的原型链设置为注入之前的任何C。

我认为这很简单,就像

C extends (B extends C.prototype)

但不幸的是,由于coffeescript所做的所有原型/ __ super__魔术,事情并不那么简单。 有没有人知道如何注入原型链,这基本上就像你说class C extends Bclass B extends A首先class B extends A

非常感谢。

澄清:以下代码不起作用,因为属性无法复制。

class A
  foo: 1
class B
  bar: 2
class C extends A
  baz: 3

B extends A
C extends B

c = new C
console.log c.foo
console.log c.bar
console.log c.baz

[ 更新:我原来回答说C extends B; B extends A C extends B; B extends A会起作用。 这确实使C instanceof BB instanceof A变为true ,但它不会根据需要复制原型属性。 所以,我改写了答案。]

让我们来看看:

class A
  foo: 1
class B
  bar: 2
class C extends A
  baz: 3

此时, C::foo为1, C::baz为3.如果我们再运行

C extends B

B的实例( child.prototype = ... )覆盖C的现有原型,因此只定义了C::bar

当我们使用class X extends Y语法时,这不会发生,因为属性仅在其原型被覆盖后附加到X的原型。 所以,让我们写一个包装周围extends ,节省了现有的原型属性,然后恢复它们:

inherits = (child, parent) ->
  proto = child::
  child extends parent
  child::[x] = proto[x] for own x of proto when x not of child::
  child

将此应用于我们的示例:

inherits B, A
inherits C, B

console.log new C instanceof B, new B instanceof A  # true, true
console.log B::foo, B::bar, B::baz  # 1, 2, undefined
console.log C::foo, C::bar, C::baz  # 1, 2, 3

如果您想了解更多有关CoffeeScript类的内部工作原理的信息,您可能需要查看我的关于CoffeeScript的书 ,该书由PragProg的优秀人员发布。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM