Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are __defineGetter__() and __defineSetter__() functions?

Tags:

javascript

What are __defineGetter__() and __defineSetter__() functions in prototype of every Object?

like image 364
Sergey Metlov Avatar asked Jul 26 '11 04:07

Sergey Metlov


People also ask

What is __ proto __ JS?

__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).

What is a getter in JavaScript?

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed.


Video Answer


2 Answers

See the MDN docs here for a description and example code:

A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties.

As noted in the docs (and by @ cwallenpoole), __define[GS]etter__() functions are now deprecated. There's a lot more detail in this article. I believe the defineProperty() function is now the preferred syntax.

like image 167
nrabinowitz Avatar answered Sep 22 '22 19:09

nrabinowitz


To answer your question __defineGetter__() and __defineSetter__() are the old/original way to create a getter and a setter for an object's property. They allow you use an object's property as a name/value pair while behind the scenes these name/value pairs are supported by functions.

For example, let's say you wanted to reference some random numbers in fixed ranges. You could express these as words with the maximum of the range and it would look like a property.

var random = {}; random.__defineGetter__('ten', function() {      return Math.floor(Math.random()*10); }); random.__defineGetter__('hundred', function() {      return Math.floor(Math.random()*100); }); 

Note that the while the above example answers the question you should not use this solution. Instead you should use the modern form of getters and setters since ES5:

var random = {     get ten() { return Math.floor(Math.random()*10); },     get hundred() { return Math.floor(Math.random()*100); } }; 

Either of the above constructs would allow you to get a random number like this:

var myrand = random.ten; // returns a result in the range 0 to 9 
like image 21
Guy Avatar answered Sep 21 '22 19:09

Guy