/    /  Javascript-Setters

Javascript-Setters

 

setter takes an argument and sets the property value inside the object to that passed argument.

 

Syntax:

 

{set prop(val) { . . . }}
{set [expression](val) { . . . }}

 

Parameters:

 

prop: Name of the property to bind to the given function.

Val: The variable that holds the value attempted to be assigned to prop.

expression: Starting with ECMAScript 2015, and use expressions for a computed property name to bind to the given function().

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Getters and Setters</h2>

<p>Getters and setters allow you to get and set properties via methods.</p>

<p>This example uses a lang property to set the value of the language property.</p>

<p id="set"></p>

<script>
// Create an object:
var person = {
 firstName: "John",
 lastName : "Doe",
 language : "NO",
 set lang(value) {
  this.language = value;
  }
};
// Set a property using set:
person.lang = "Telugu";
// Display data from the object:
document.getElementById("set").innerHTML = person.language;
</script>

</body>
</html>

 

OUTPUT:

 

JavaScript Getters and Setters

Getters and setters allow you to get and set properties via methods.

 

This example uses a lang property to set the value of the language property.

 

Telugu