【发布时间】:2014-11-28 01:47:32
【问题描述】:
使用下面的 someAPI,它需要我想在构造函数中动态分配的凭据。然后我想在整个课程中使用 someAPI。 IE。在下面的示例中,someMethodUsingSomeAPI 是我想从 B 实例中的其他方法调用的辅助方法。Coffee-/JavaScript 可以做到这一点吗? (我可以让它工作的唯一方法是将 someMethodUsingSomeAPI 放在构造函数中。)
SomeAPI = Npm.require 'someAPI'
class B extends A
constructor: (options = {}) ->
unless @ instanceof B
return new B(options)
@config = JSON.parse(Assets.getText('config/' + options.username + '.json'))
@someAPI = new SomeAPI
consumer_key: @config.credentials.consumer.key
consumer_secret: @config.credentials.consumer.secret
access_token: @config.credentials.access.token
access_token_secret: @config.credentials.access.secret
someMethodUsingSomeAPI = Async.wrap((id, callback) ->
return @someAPI.get 'whatever/show', { 'id': id }, callback
)
console.log someMethodUsingSomeAPI '123' # Error: Cannot call method 'get' of undefined
根据 saimeunt 的建议进行了更新
...
someMethodUsingSomeAPI = (id) ->
wrappedGet = Async.wrap(@someAPI, 'get')
wrappedGet 'whatever/show', { id: id }
console.log someMethodUsingSomeAPI '123' # ReferenceError: someMethodUsingSomeAPI is not defined
&
b = B('username')
b.someMethodUsingSomeAPI '123' # Works!
将someMethodUsingSomeAPI: 更改为someMethodUsingSomeAPI =
console.log someMethodUsingSomeAPI '123' # Error: unsupported argument list
&
b = B('username')
b.someMethodUsingSomeAPI '123' # TypeError: Object #<B> has no method 'someMethodUsingSomeAPI'
(这是 Meteor 0.9.3.1)
更新试图澄清
Here's a simplified version of the above, without any of the API stuff.
someMethod = works, someMethod: doesn't work
我很高兴classInstance.someMethod 在使用 : 时可以正常工作,但我真的很想让它在实际实例中工作。
【问题讨论】:
-
为什么要将
someAPI设为类外部的静态变量,而不是实例property? -
请注意,
JSON.parse确实采用 JSON 字符串,而不是文件路径。 -
是的,很抱歉。为简洁起见,只是删除了一些。加回来了。
-
您使用
someMethodUsingSomeAPI =应该是someMethodUsingSomeAPI:。然后,实例化B,并在其上调用方法。或者你为什么要定义一个类? -
如果我将它从 = 更改为 :,我会得到
ReferenceError: someMethodUsingSomeAPI is not defined和上面的跟踪。如果我这样做B.someMethodUsingSomeAPI '123',我会得到Cannot call method 'get' of undefined。我想从 B 中的其他方法调用这个辅助方法。
标签: javascript oop design-patterns meteor coffeescript