在下面的一些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