使用 coffeescript 公开一个 javascript api [英] Expose a javascript api with coffeescript

查看:17
本文介绍了使用 coffeescript 公开一个 javascript api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用coffeescript,并且很好奇将我用Coffeescript 创建的对象公开给其他javascript 页面的正确"方式是什么.由于咖啡脚本包装功能,调用 window.coffeeObject = externalObject 是否可以接受.

I recently started using coffeescript and was curious what is the "right" way to expose an object that I create with Coffeescript to other javascript pages. Because of coffeescripts wrapping functionality, is it acceptable behavior to call window.coffeeObject = externalObject.

example.coffee

externalObject = 
   method1: -> 'Return value'
   method2: -> 'Return method2'

window.myApi = externalObject

example.js -- 编译自example.coffee

example.js -- compiled from example.coffee

(function() {
  var externalObject;
  externalObject = {
    method1: function() {
      return 'Return value';
    },
    method2: function() {
      return 'Return method2';
    }
  };
  window.myApi = externalObject;
}).call(this);

other.js

alert(myApi.method1()) // Should return "Return value"

推荐答案

是的,没错.或者,您可以使用 define @myApi = { foo: ->} 因为 this 是文件根上下文中的 window.

Yep that's correct. Alternatively you can use define @myApi = { foo: -> } because this is window in the root context of the file.

这篇关于使用 coffeescript 公开一个 javascript api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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