我想在类属性中嵌套多个函数,如下所示。
不幸的是,他们无法访问该类的主要范围。
我可以在不传递每个嵌套函数引用的情况下解决这个问题吗this
?
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
使用建议的粗箭头的非工作替代方案:
class myClass
constructor: ->
@errors = []
@functions:
doStuff: =>
@errors.push "I wont work either" # TypeError: Cannot call method 'toString' of undefined
可选替代方案,不写入全局this.errors
财产:
class myClass
constructor: ->
@functions =
errors: []
doStuff: ->
@errors.push "I will write to functions.errors only"
在 JavaScript 中(因此,CoffeeScript 也是如此),方法使用this
包含方法的对象的。
method() // this == globalObject
object.method() // this == object
Math.random() // this == Math
这通常效果很好,除非你处理像你这样的例子:
object.functions.method() // this == object.functions
在处理 JavaScript 时,我会避免使用函数的命名空间 - 即使有解决方法,它也不能很好地发挥作用。例如,您可以尝试引用this
对象在object.functions
,所以任意函数object.functions
将有权访问它。
class MyClass
constructor: ->
@errors = []
@functions.self = this
doSomething: ->
@errors.push "I work as expected"
functions:
alsoDoSomething: ->
@self.errors.push "Also works!"
这乍一看似乎有效,但当您使用以下属性时可能会感到困惑apply
or call
on it, obj1.functions.alsoDoSomething.call(obj2)
不会像obj2
不是正确的对象(用户应该这样做obj2.functions
相反,这可能会令人困惑)。
真正的解决方案是:don't。 JavaScript 不适合这样的滥用。所有对象方法都应该直接位于对象原型中。如果其中有对象,则它的所有方法都不是对象的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)