gpt4 book ai didi

javascript - Coffeescript 类中的方法返回函数而不是字符串

转载 作者:行者123 更新时间:2023-12-02 16:29:14 26 4
gpt4 key购买 nike

我只是想调用一个函数,该函数从动态构建的继承类中以字符串形式返回 Url:

class @Api

DEFAULT_API_VERSION: 'v2'

constructor: ->
@setVersion(@DEFAULT_API_VERSION)
return

setVersion: (version) ->
@version = version if version?

getVersion: ->
@version

baseUrl: ->
"http://api#{@getVersion()}.mysite.com/api/#{@getVersion()}/"

class @ApiArticle extends Api

constructor: ->
super
return

articlesUrl: ->
"#{@baseUrl}news/articles".toString()

这是父类中的测试,通过

  it 'provides the baseUrl for Api calls', ->
api = new Api()
expect(api.baseUrl()).toEqual('http://apiv2.mysite.com/api/v2/')

这是我的测试,它失败

it 'returns all news articles url', ->
new ApiArticle()
url = api_article.articlesUrl()
expect(url).toEqual 'http://apiv2.mysite.com/api/v2/news/articles'

我从这个规范得到的结果,它应该是一个字符串,但收到这个:

 Expected
'function () { return "http://api" + (this.getVersion()) + ".mysite.com/api/" + (this.getVersion()) + "/"; }news/articles'
to equal
'http://apiv2.mysite.com/api/v2/news/articles'.

是不是少了什么东西?我必须显式渲染/计算吗?

我对 JS 和 Coffee 还很陌生。

谢谢!

最佳答案

这里

articlesUrl: ->
"#{@baseUrl}news/articles".toString()

您想调用父类(super class)中的方法baseUrl,但您只是引用了它。因此,函数本身会被 toString 编辑,并附加“新闻/文章”。这会产生字符串: function () { return "http://api"+ (this.getVersion()) + ".mysite.com/api/"+ (this.getVersion()) + "/”; }news/articles,这是您在测试错误中看到的内容。

通过实际调用 baseUrl 来修复它,而不仅仅是引用它:

articlesUrl: ->
"#{@baseUrl()}news/articles".toString()

然后您可以删除无用的 toString 调用。

您可能需要考虑重命名方法 getBaseUrl 以避免再次犯此错误。

关于javascript - Coffeescript 类中的方法返回函数而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28454166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com