javascript - Coffeescript 编译参数名称错误的构造函数

标签 javascript angularjs coffeescript

我第一次尝试将 Coffeescript 与 AngularJS 一起使用。

我想定义一个与服务$http有依赖关系的新服务

这是我所期待的:

var MyService = function($http) {
    this.$http = $http;
};

MyService.prototype.call = function(url, data) {
  this.$http(url, data);
};

myApp.service("webService", MyService)

这是注册服务的正常方法,如 AngularJS 文档中所示。

阅读了一篇有关使用 Coffeescript 和 AngularJS 的文章后,我尝试了以下方法:

myApp.service "webService", class
    constructor : (@$http) ->
    call : (url, data) -> @$http url, data

但是编译的结果给出了这个 javascript:

myApp.service("webService", (function() {
    function _Class(_at_$http) {
        this.$http = _at_$http;
    }

    _Class.prototype.call = function(url, data) {
        return this.$http(url, data);
    };

    return _Class;

})());

问题是 Coffeescript 编译器不应将 @$http 替换为 _at_$http。就我而言,它应该输出以下 javascript:

myApp.service("webService", (function() {
    function _Class($http) {
        this.$http = $http;
    }

    _Class.prototype.call = function(url, data) {
        return this.$http(url, data);
    };

    return _Class;

})());

您可以查看online compiler on Coffeescript website给出了预期的结果,所以我不明白为什么我的效果不好。

我需要这个,因为 Angular 注入(inject)引擎无法识别 _at_$http 因为它需要 $http 参数名称。

最佳答案

您需要升级到 CoffeeScript 1.9.1 or higher :

  • Internal compiler variable names no longer start with underscores. This makes the generated JavaScript a bit prettier, and also fixes an issue with the completely broken and ungodly way that AngularJS "parses" function arguments.

如果您无法升级,那么您可以手动连接实例变量:

constructor : ($http) -> @$http = $http

CoffeeScript.org 一切正常。因为他们始终运行最新版本。

关于javascript - Coffeescript 编译参数名称错误的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718501/

相关文章:

javascript - 在 MVC View 中使用 C# 属性时未设置变量

javascript - 如何设置带有格式化日期的 jQuery DatePicker?

javascript - Angular 模块的可扩展全局配置

javascript - 如何获得具有特定属性的嵌套对象的计数?

javascript - 需要在另一页上 $save()

css - chardinjs 不能在 ruby​​ on rails 中工作

javascript - ES6 全局符号是否被垃圾收集?

javascript - 动画 scrollTop 不工作

clojure - map 重组

syntax - coffeescript throw Error("ExecJS::RuntimeError: SyntaxError: unexpected , 在函数中