javascript get set code example

Example 1: getters and setters javascript

let obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    if (this.log.length === 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
};

obj.log.push('d');
console.log(obj.latest); //output: 'd'

Example 2: set get javascript

var person = {
  language : "en",
  get lang() { return this.language; },
  set lang(lang) { this.language = lang; }
};
document.getElementById("demo").innerHTML = person.lang;
person.lang = "es";

Example 3: getter and setters in js

var person={firstname:"chetha",secondname="kumar",get fullname()
{
  	return this.firstname+" "+this.secondname;
}
document.write(person.fullname);
var person={firstname:"chethan",secondname="kumar",course:"",set course(x)
{
  	this.course=x;
}
person.course="bca";
document.write(person.course);

Example 4: javascript class setter

const language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN';
language.current = 'FA';

console.log(language.log);

Example 5: get set

class Thing {
  private int secret; // This is a field.

  public int Secret { // This is a property.
    get {
      Debug.Print("Somebody is accessing the secret!");
      return secret;
    }

    set {
      Debug.Print("Somebody is writing to the secret!");
      secret = value; // Note the use of the implicit variable "value" here.
    }
  }
}

Tags:

Html Example