Skip to main content
gamedev.net
🔒 Locked

Javascript closures?

Started by Epp 2 replies 500+ views
Original Post
Epp
Epp
Is the function returned by the repeater function from this post really a closure?

function repeater(n) {
  return function(w) {
    for (var r = '', i = [0]; i < n; i++) {
      r += w;
    }
    return r;
  }
}

Because it can still access and modify the global variable scope which Wikipedia states closures can't. But Wikipedia also states that javascript supports closures, so how do you write them?
ToohrVyk
ToohrVyk
Use the same syntax, but don't access or modify global variables.

As a side note, if a closure contains a mutable object (for instance, a global mutable object), it can modify that object.
Epp
Epp
Yes but can you still call it a closure if you just don't access or modify global variables. If so any normal function which doesn't access or modify global variables would be a closure.
kSquared
kSquared
Quote:
Original post by Epp
Yes but can you still call it a closure if you just don't access or modify global variables.

Yes, you can. A construct is a closure if it satisfies certain properties. Merely because these properties are not enforced by the compiler doesn't change the fact that it's still a closure.
- k2 "Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ<

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.