2

I want to prevent editing of a particular key's value of an object. means it should be initialized only once. suppose there is a constructor function Student(fname,lname,id).

function Student(fname,lname,id){
     this.fname = fname;
     this.lanme= lname;
     this.id= id;
}

var st1 = new Student ('surya','pratap',1)

I want to prevent the modification of Id only for st1.fname and lname can be modified.

spratap124
  • 151
  • 2
  • 10
  • This sounds like an [X/Y Problem](http://xyproblem.info/). What is the purpose of this requirement? – Phil Sep 05 '18 at 05:17
  • @Phil I think the question of how to use read-only properties is a perfectly reasonable question on SO. – csum Sep 05 '18 at 05:36
  • @csum I didn't say it wasn't. What I'm after is some clarity around the expected use. For example, OP might consider this a way to prevent tampering with records stored behind an API but it won't actually stop a malicious user if the `Student` object is serialised as JSON – Phil Sep 05 '18 at 05:44
  • @Phil I'm with csum on this one. I'll ask for a clarification if the question asks for something weird like "how do I list files in bash without ls", but this is a pretty reasonable question. – Amadan Sep 05 '18 at 06:28
  • FYI, I'm not trying to close this question or suggest that it's not a good one. I just want to know **why** OP wants to make the field read-only – Phil Sep 05 '18 at 06:32

2 Answers2

4

There are a couple of ways to achieve this, by far easiest way you can achieve this is the following:

function Student(fname,lname,id){
     this.fname = fname;
     this.lanme= lname;
     this.id=id;
     Object.defineProperty(this, "id", {
      writable: false,
      value: id,
      configurable: false
    });
}
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
  • 1
    You do not need `this.id=id;` any more there. It will be overwritten by `Object.defineProperty`. – Amadan Sep 05 '18 at 06:23
0

In es6 you can do that using Symbols:

const 
  ID = Symbol(),
  NAME = Symbol()
;

export default class Student {

  constructor(id, name) {
    this[ID] = id;
    this[NAME] = name;
  }

  get id () { return this[ID]; }

  get name () { return this[NAME]; }
}
philipp
  • 15,947
  • 15
  • 61
  • 106