在下面的一些API中,它需要我想在构造函数中动态分配的凭据。然后我想在整个班级中使用一些API。即在下面的例子中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'
(这与流星0.9.3.1)
UPDATE IN试图澄清
Here's a simplified version of the above, without any of the API stuff.
someMethod = works,someMethod: doesn't work
我很高兴classInstance.someMethod在使用时有效,但真的很想让它在实际情况下工作。
为什么让'someAPI'静态变量类之外,而不是实例*物业,*? – Bergi 2014-10-03 00:45:27
请注意,'JSON.parse'确实需要一个JSON字符串,而不是文件路径。 – Bergi 2014-10-03 00:45:52
对,对不起。为简洁起见,删除了一些内容。加回来。 – jiku 2014-10-03 01:02:05