在CoffeScript中定义外部范围的类 [英] defining classes for outer scope in CoffeScript

查看:190
本文介绍了在CoffeScript中定义外部范围的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前问题的后续 Javascript:ReferenceError:MyClass未定义

This is a follow up to my previous question Javascript: ReferenceError: MyClass is not defined.

.coffee文件转换为.js将创建一个 MyClass 仅在其范围内。

A .coffee file with this converted to .js will create a MyClass available only inside its scope.

class MyClass
    name: (name) -> 

CoffeScript中有没有办法使类可用于外部范围?我应该能够< script src .. HTML页面上的文件,并从控制台实例化类。

Is there a way in CoffeScript to make the class available to the outer scope? I should be able to <script src.. the file on a HTML page and instantiate the class from the console.

推荐答案

无论你怎么做,你都会污染全局范围。

You'll "pollute the global scope" no matter how you do it. It's just a matter of how you do it.

CoffeeScript中的 @ 符号用于表示此范围。所以你甚至可以在类定义中使用它。类声明的结果是该类在窗口对象的范围内定义(除非有一些其他情况,但这不太可能在你描述的内容中这里)。

The @ symbol in CoffeeScript is used to mean "this scope". So you can even use it on a Class definition. The result on a class declaration is that the class is defined in the scope of the window object (unless there are some other circumstances, but that's not likely in what you're describing here).

class @CustomClassName
    constructor: -> 
        # constructor stuff goes down...






但是,我喜欢这样做与命名空间,个人。
考虑 google.maps.Map ,或者如果您曾撰写过Actionscript 3: flash.display.MovieClip


However, I prefer to do this with a namespace, personally. Think about google.maps.Map or if you've ever written Actionscript 3: flash.display.MovieClip.

在CoffeeScript文件的顶部放置了如下行:

At the top of your CoffeeScript file put something along the lines of this:

window.customnamespace = window.customnamespace || {}

现在创建课程时,您可以说:

Now when you create your class, you can say:

class customnamespace.ClassName
    constructor: (container) ->
        # set the container
        @container = container
        # etc...

class customnamespace.OtherClassName
    constructor: ->
        # Another class...

document.ready

In your document.ready (if you're using jQuery) you'll globally have access to that namespace and all its classes.

例如:

$(document).ready(function(e) {
    var c = new customnamespace.ClassName($('#container'));

    var other = new customnamespace.OtherClassName();

有意义吗?

这篇关于在CoffeScript中定义外部范围的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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