Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Last active August 6, 2019 07:43
Show Gist options
  • Save xiaoyunyang/0bc36a0e35d9ead6732a61ae2e8a2ae6 to your computer and use it in GitHub Desktop.
Save xiaoyunyang/0bc36a0e35d9ead6732a61ae2e8a2ae6 to your computer and use it in GitHub Desktop.
Closure Example - Object Oriented Programming
function Person(name) {
var secret = “secret!”
this.name = name
this.setName = function(newName) { this.name = newName }
this.setNameToFoo = function() { this.name = foo }
this.getSecret = function() { return secret }
}
 
var a = new Person(“Max”)
 
a.name //> “Max”
a.setName(“Oliver”)
a.name //> “Oliver”
a.setNameToFoo() //> ERROR: foo is undefined
 
var foo = “Foo”
a.setNameToFoo()
a.name //> “Foo”
 
a.secret //> undefined
a.getSecret() //> “Secret!”
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment