JavaScript'inizde
class myClass
constructor: -> @errors = []
doSomething: -> @errors.push "I work as expected"
functions:
doStuff: ->
@errors.push "I cant access @errors" # => TypeError: Cannot call method 'push' of undefined
ugly: (context) ->
context.errors.push "It works, but I am ugly" # Works fine but requires scope injection
Ateş etmeyen alternatif yağ oku önerdi kullanarak , CoffeeScript de), yöntem, yöntemi içeren nesnenin this
kullanın. Eğer sizin gibi örnek başa sürece
method() // this == globalObject
object.method() // this == object
Math.random() // this == Math
Bu genellikle, iyi çalışıyor:
object.functions.method() // this == object.functions
JavaScript ile uğraşırken, ben fonksiyonlar için ad olan önleyeceğini - bu geçici çözümler ile bile, iyi oynamıyor . Örneğin, object.functions
'da this
nesnesine başvuruda bulunmayı deneyebilirsiniz, böylece object.functions
'daki herhangi bir işlev buna erişebilir.
Bu, ilk çalışmaya, ancak
obj2
gibi çalışmaz
apply
ya da üzerinde
call
,
obj1.functions.alsoDoSomething.call(obj2)
gibi özelliklerini kullanırken kafa karıştırıcı olabilir görünür
class MyClass
constructor: ->
@errors = []
@functions.self = this
doSomething: ->
@errors.push "I work as expected"
functions:
alsoDoSomething: ->
@self.errors.push "Also works!"
hangi olamaz, doğru nesne (kullanıcı yerine obj2.functions
yapmalıyım kafa karıştırıcı olmak).
Gerçek çözüm şu şekildedir: . JavaScript, bu gibi kötüye kullanım amaçlı değildir. Tüm nesne yöntemleri doğrudan nesne prototipinde olmalıdır. İçinde nesneniz varsa, bunun tüm yöntemleri nesnenizin yöntemleri değildir.
Bu/@ yapıcıya bunları bağlamak için? – biziclop
Yani yapıcı: -> @errors = [] @functions: doStuff -> ... '? – Industrial
Belki de yağ oku kullanarak => http://coffeescript.org/#fat_arrow Ben bir coffeescript ustası değilim, üzgünüm :) – biziclop