Javascript:ReferenceError:MyClass未定义 [英] Javascript: ReferenceError: MyClass is not defined

查看:184
本文介绍了Javascript:ReferenceError:MyClass未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是非常基本的。我尝试实例化在嵌入的外部.js文件中定义的类。 .js的代码就是这样。

This is very basic. I try to instantiate a Class defined in an external .js file embedded. The code of the .js is simply this.

(function() {
  var MyClass;

  MyClass = (function() {

    function MyClass() {}

    MyClass.prototype.name = function(name) {};

    return MyClass;

  })();

}).call(this);

HTML是这样

<!DOCTYPE html>
<html>

  <head>
    <title>Sample Page</title>
    <script src="file.js" type="text/javascript"></script>
  </head>

  <body>

  </body>
</html>

如果我尝试在控制台实例化类,但我看到一个 ReferenceError :MyClass未定义

If I try on the console to instantiate the class but I see a ReferenceError: MyClass is not defined:

var myVar
myVar = new MyClass
> ReferenceError: MyClass is not defined

如果我尝试调用 MyClass 直接从控制台我得到相同的错误

If I try to call MyClass directly from console I get the same error

> ReferenceError: MyClass is not defined

我确定我在这里缺少一些可怕的东西,它出来了什么。

I'm sure I missing something terrible obvious here but yet I can figure it out what.

更新:要创建JavaScript编码,我正在使用CoffeScript,代码就是这样。

Updated: To create the javascript coded I'm using CoffeScript, the code is simply this.

class MyClass
  acc: (name) ->

当使用 http://js2coffee.org 渲染到不同的代码,它仍然不工作。 Wonder如果CoffeScript有一个提示,将MyClass从局部范围弹出到外部范围。

The proposed answers codes when converted back to CoffeScript using http://js2coffee.org render into a different code and it still doesn't work. Wonder If there's a hint on CoffeScript to eject MyClass from local scope to the outer scope.

推荐答案

。而你想做的是通过将其设置到窗口对象弹出到外部范围:

My class is defined inside a closure. Rather what you want to do is "eject" it into the outer scope by setting it to the window object:

(function() {

    var myClass = ...

    window.myClass = myClass;

}).call( this );

更新:好像你想在CoffeeScript中使用它。您在这里:

Update: It seems you wanted it in CoffeeScript. Here you go:

(->

  myClass = (->
    myClass = ->
    myClass::name = (name) ->

    myClass
  )()

  window.myClass = myClass

).call this

JSBin演示

JSBin Demo

这篇关于Javascript:ReferenceError:MyClass未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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