简体   繁体   English

CoffeeScript中的返回方法

[英]Return method in CoffeeScript

How to I do this in CoffeeScript: 我如何在CoffeeScript中执行此操作:

window.onload = function() {
  test.init();
};

var test = (function() {
  var num = 1;

  var pub = function() {
    document.body.innerHTML = num;
  };

  return {
    init: function() {
      pub();
    }
  }

}());

JSFiddle 的jsfiddle

It looks like this should do the trick: 看起来这应该可以解决问题:

window.onload = -> test.init()

test = do ->
  num = 1
  pub = -> document.body.innerHTML = num
  init: -> pub()

Or this, if you explicitly don't want the functions to return anything: 或者,如果您明确不希望函数返回任何内容:

window.onload = ->
  test.init()
  return

test = do ->
  num = 1
  pub = ->
    document.body.innerHTML = num
    return
  init: ->
    pub()
    return

This translates quite one-by-one: 这个翻译很简单:

window.onload = ->
  test.init()

test = do ->
  num = 1
  pub = ->
    document.body.innerHTML = num;

  init: ->
    pub()

( compile ) 编译

However, you might shorten it (and the js similarly) to just 但是,你可以缩短它(和js类似)

test = do ->
  num = 1
  init: ->
    document.body.innerHTML = num;
window.onload = test.init

( compile ) 编译

Optionally, you can insert empty parenthesis (no parameters) before every -> . (可选)您可以在每个->之前插入空括号(无参数)。

js-2-coffee is a really handy website for this kind of thing in the future js-2-coffee将来会成为一个非常方便的网站

It gives the following coffeescript when you paste in your javascript 当您粘贴javascript时,它会提供以下coffeescript

window.onload = ->
  test.init()
  return

test = (->
  num = 1
  pub = ->
    document.body.innerHTML = num
    return

  init: ->
    pub()
    return
())

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

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