class @ChatApp # public constructor: (config) -> @dispatcher = new WebSocketRails(window.location.host + "/websocket") bindEvents() log: (message) => $('#chat_history').append message #private bindEvents = -> console.log this # указывает на window console.log @dispatcher # undefined console.log @log # undefined @dispatcher.bind 'log', @log # немного исправляет ситуацию, если написать bindEvents = => console.log this # заменяется на ChatApp console.log @dispatcher # ChatApp.dispatcher = undefined console.log @log # ChatApp.log = undefined @dispatcher.bind 'log', @log 

the code gives an Uncaught TypeError: Cannot read property 'bind' of undefined error Uncaught TypeError: Cannot read property 'bind' of undefined

  • the easiest way to pass a created object is by parameter - Grundy
  • I also thought about it, but this is some kind of ugly option - srghma
  • If you look at what your code is transformed into, this is the only way to keep the function private. Well, except to call bind directly in the constructor - Grundy
  • that's what it translates to with bindEvents = => - srghma
  • That's it: bindEvents is an ordinary local function, not related to the object being constructed. Therefore, without passing by the parameter, or by setting this manually, you can’t refer to the object being created - Grundy

1 answer 1

Following the article , private non-static methods should be created in the constructor, as in this example.

 # CoffeeScript class Square # private static variable counter = 0 # private static method countInstance = -> counter++; return # public static method @instanceCount = -> counter constructor: (side) -> countInstance() # side is already a private variable, we define a private variable `self` to avoid evil `this` self = this # private method logChange = -> console.log "Side is set to #{side}" # public methods self.setSide = (v) -> side = v logChange() self.area = -> side * side s1 = new Square(2) console.log s1.area() # output 4 s2 = new Square(3) console.log s2.area() # output 9 s2.setSide 4 # output Side is set to 4 console.log s2.area() # output 16 console.log Square.instanceCount() # output 2 

but this is not suitable for my project, so I make the bindEvents method open