Does Javascript have get/set keywords like C#?

回眸只為那壹抹淺笑 提交于 2019-11-29 01:20:25

As suggested by Martinho, here are some links explaining the getter/setters in JS 1.5:

http://ejohn.org/blog/javascript-getters-and-setters/

http://ajaxian.com/archives/getters-and-setters-in-javascript

Be aware though, they don't seem to be supported in IE, and some developers have (legitimate) concerns about the idea of variable assignment having side-effects.

get/set are not reserved keywords as Daniel points out. I had no problem creating a top-level functions called "get" and "set" and using the alongside the code-sample posted above. So I assume that the parser is smart enough to allow this. In fact, even the following seems to be legitimate (if confusing):

var Sample = {
   bs : "",
   get get() { return this.bs; },
   set get(val) { this.bs = val; }
 }

According to Mozilla, they are not in ECMAScript.

JavaScript Setters And Getters:

Usually the setter and getter methods follow the following syntax in JavaScript objects. An object is created with multiple properties. The setter method has one argument, while the getter method has no arguments. Both are functions.

For a given property that is already created within the object, the set method is typically an if/else statement that validates the input for any time that property is directly accessed and assigned later on via code, a.k.a. "set". This is often done by using an if (typeof [arg] === 'certain type of value, such as: number, string, or boolean') statement, then the code block usually assigns the this.(specific)property-name to the argument. (Occasionally with a message logging to the console.) But it doesn't need to return anything; it simply is setting the this.specific-property to evaluate to the argument. The else statement, however, almost always has a (error) message log to the console that prompts the user to enter a different value for the property's key-value that meets the if condition.

The getter method is the opposite, basically. It sets up a function, without any arguments, to "get", i.e. return a(nother) value/property when you call the specific-property that you just set. It "gets" you something different than what you would normally get in response to calling that object property.

The value of setters and getters can be easily seen for property key-values that you don't want to be able to be directly modified, unless certain conditions are met. For properties of this type, use the underscore to proceed the property name, and use a getter to allow you to be able to call the property without the underscore. Then use a setter to define the conditions by which the property's key-value can be accessed and assigned, a.k.a. "set". For example, I will include two basic setters and getters for this object's properties. Note: I use a constant variable because objects remain mutable (after creation).

const person = {
_name: 'Sean';
_age: 27;

set age(ageIn) {
if (typeof ageIn === 'number') {
  this._age = ageIn;
}
else {
  console.log(`${ageIn} is invalid for the age's key-value. Change ${ageIn} to/into a Number.`);
  return 'Invalid Input.';
}
},

get age() {
return this._age;
},

set name(nameIn) {
if (typeof nameIn === 'string') {
        this._name = nameIn;
      } else {
        console.log(`Change ${nameIn} to/into a(ny) String for the name's 
key-value.`);
        return 'Invalid Input.';
    }
},

get name() {
return this._name;
}

};

Where it gets interesting is when you try to set/assign a new key-value for the _age property, because it has to meet the if conditional in order to be successfully assigned, meaning not all assignments are valid, etc.

person.age = 'twenty-eight'; /* output: twenty-eight is invalid for the 
age's key-value.  Change twenty-eight to/into a Number. */
console.log(person.age); // output: 27 (twenty-eight was never assigned)
person.age = 28; // output: none
console.log(person.age); // output: 28

Note how I was able to access the person._age property via the person.age property thanks to the getter method. Also, similar to how input for age was restricted to numbers, input for the name property is now restricted/set to strings only.

Hope this helps clear things up! Additionally, some links for more:

https://johnresig.com/blog/javascript-getters-and-setters/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

https://www.infragistics.com/community/blogs/infragistics/archive/2017/09/19/easy-javascript-part-8-what-are-getters-and-setters.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!