【问题标题】:Coffescript compile constructor with wrong argument nameCoffeescript 编译构造函数的参数名称错误
【发布时间】:2017-09-24 13:56:31
【问题描述】:

我第一次尝试将 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 编译器不应该用_at_$http 替换@$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 给出了预期的结果,所以我不明白为什么我的工作不好。

我需要这个,因为角喷射引擎无法识别 _at_$http,因为它需要 $http 参数名称。

【问题讨论】:

    标签: javascript angularjs coffeescript


    【解决方案1】:

    你需要升级到CoffeeScript 1.9.1 or higher:

    • 内部编译器变量名称不再以下划线开头。这使得生成的 JavaScript 更漂亮一些,并且还解决了 AngularJS“解析”函数参数的完全破坏和不虔诚的方式的问题。

    如果你不能升级,那么你可以手动连接实例变量:

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

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

    【讨论】:

    • 非常感谢!我没有检查咖啡脚本更新的想法^^
    猜你喜欢
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多