javascript - 有没有类似 Ruby 的 JavaScript 模块

标签 javascript ruby module mixins es6-class

假设我有一个 Ruby 类和一个 Ruby 模块

module Foo
  def hello
    puts 'hello'
  end
end

class Bar
  include Foo
end

现在我可以做这样的事情了

Bar.new.hello 

我可以在 JavaScript 中做同样的事情吗?我不能使用 extends 关键字,因为我的 JavaScript 类已经被继承了。我怎样才能将一些功能混合到我的类中?

已更新

我想使用一些与 ES6 类一起工作的东西

最佳答案

我确实建议阅读我在 SO 上给出的一些列出的答案,这些答案与 OP 的非常相关。

... 编辑:顺便说一下,搜索“es6 classes mixins”确实已经指向了Mixins for ES6 classes, transpiled with babel。 ...

使用 OP 的例子,一个已经可靠的答案可能会被简单地分解为......

function withSayHello() {       // - function based *Flight Mixin* as of Angus Croll.
  this.sayHello = function () { // - should be encouraged becoming the main approach
                                //   (though featuring a sugared syntax) of a future
    console.log(this.hello);    //   *Lightweight Trait* implementation.
  };                            //
}                               //

function Bar() {                // - classic ES3 constructor.
    this.hello = 'hello';       //
                                //
    withSayHello.call(this);    // - applying the function based Mixin/Trait/Talent
}                               //   from above.
var bar = new Bar;

bar.sayHello();


class Foo {                     // - with syntactic "class" sugar ...
  constructor() {               //   ... `constructor` does remain the place for ...
    this.hello = 'Howdy!';      //
                                //
    withSayHello.call(this);    //   ... applying function based Mixins/Traits/Talents.
  }                             //
}                               //
var foo = new Foo;

foo.sayHello();

也可以用 Babel's REPL 检查上面的例子.

浏览器仍然不支持 JavaScript 的标准化模块系统。另一方面,例如JS 库和 NodeJS 环境确实提供了它们自己的模块系统。 上面的工作示例很容易在每个示例中进行传输/转换——但这里又变成了标准示例,因为它已经得到编译器的支持,例如 Babel。和 Traceur .

// module "my_special_withSayHello_mixin.js"
//
export default function withSayHello() {
  this.sayHello = function () {

    console.log(this.hello);
  };
}


// module "my_very_own_Foo_implementation.js"
//
import withSayHello from 'my_special_withSayHello_mixin';

export default class Foo {
  constructor() {
    this.hello = 'Howdy!';

      withSayHello.call(this);
  }
}


// module "main.js"
//
import Foo from 'my_very_own_Foo_implementation';

var foo = new Foo;
foo.sayHello();

关于javascript - 有没有类似 Ruby 的 JavaScript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40451954/

相关文章:

ruby-on-rails - phusion passenger 和 ruby​​ 1.9.1 已经开始工作了吗?

ruby - 匹配 mm/dd/yyyy hh :mm:ss AM or PM 的正则表达式

ruby - Net::HTTP.start 适用于 127.0.0.1 但不适用于 'localhost' 。为什么?

python - 字符串模块错误,python os x

javascript - 如何从模块返回管道数据?

javascript - 希望获得不断变化的 LocalStorage 值

Javascript 画廊只能运行一次

F#代码组织: types & modules

javascript - 如何使用 AngularJS 添加和删除类?

javascript - RegExp : I want to remove unnecessary words in the Sentence. 我该怎么做?