Skip to content

Instantly share code, notes, and snippets.

@tarekahsan709
Last active April 9, 2017 05:19
Show Gist options
  • Save tarekahsan709/1f7cf48a4a99abb4468aa27dcc7d0c71 to your computer and use it in GitHub Desktop.
Save tarekahsan709/1f7cf48a4a99abb4468aa27dcc7d0c71 to your computer and use it in GitHub Desktop.

We can add getter & setter in javaScript object like normal properties but secretly have methods associated with them.

var Student = {
	name: "Default",
	type: "Student",
 	get Name(){
  	return this.name;},
	set Name(name){
	 this.name = name;
	 },
	get Type(){
	  return this.type;
	 },
	 set Type(type){
	  this.type = type;
	 }
}
 var atik = Object.create(Student);
 console.log(atik.Name);
 console.log(atik.Type);

we can also add getter & setter ro an existing property. Using Object.defineProperty.

var Student = {
	name: "Default",
	type: "Student",
}

var atik = Object.create(Student);

Object.defineProperty(Student, 'Name', {
  get: function() { return this.name; },
  set: function(name) { this.name = name; }
});

 atik.Name = "Ahsan";
 console.log(atik.Name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment