Javascript 是否有像 C# 一样的 get/set 关键字?

发布于 2024-10-25 09:03:38 字数 570 浏览 3 评论 0原文

我正在使用 XULRunner,并在代码示例中遇到以下模式:

var StrangeSample = {

backingStore : "",

get foo() { return this.backingStore + " "; },

set foo(val) { this.backingStore = val; },

func: function(someParam) { return this.foo + someParam; }
};

StrangeSample.foo = "rabbit";
alert(StrangeSample.func("bear"));

这会导致“兔子熊”收到警报。

我以前从未见过 JavaScript 中使用过这种获取/设置模式。它有效,但我找不到任何文档/参考。这是 XUL 所特有的东西,是最近的语言功能,还是只是我错过的东西?我很困惑,因为几个月前我专门寻找类似的东西,但找不到任何东西。

作为参考,删除“get”或“set”会导致语法错误。将它们重命名为其他名称是语法错误。它们看起来确实是关键词。

任何人都可以为我阐明这一点,或者为我指出参考吗?

I'm working with XULRunner and came across the following pattern in a code sample:

var StrangeSample = {

backingStore : "",

get foo() { return this.backingStore + " "; },

set foo(val) { this.backingStore = val; },

func: function(someParam) { return this.foo + someParam; }
};

StrangeSample.foo = "rabbit";
alert(StrangeSample.func("bear"));

This results in "rabbit bear" being alerted.

I've never seen this get/set pattern used in Javascript before. It works, but I can't find any documentation/reference for it. Is this something peculiar to XUL, a recent language feature, or just something I missed? I'm puzzled because I was specifically looking for something like this a few months ago and couldn't find anything.

For reference, removing "get" or "set" results in a syntax error. Renaming them to anything else is a syntax error. They really do seem to be keywords.

Can anyone shed some light on this for me, or point me towards a reference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

無心 2024-11-01 09:03:38

正如 Martinho 所建议的,这里有一些解释 JS 1.5 中的 getter/setter 的链接:

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

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

但请注意,IE 似乎不支持它们,并且一些开发人员对此想法有(合理的)担忧变量赋值有副作用。

正如丹尼尔指出的那样,get/set 不是保留关键字。我毫无问题地创建了一个名为“get”和“set”的顶级函数,并使用上面发布的代码示例。所以我假设解析器足够聪明,可以允许这样做。事实上,甚至以下内容似乎也是合法的(如果令人困惑的话):

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

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; }
 }
一身仙ぐ女味 2024-11-01 09:03:38

JavaScript Setters 和 Getters:

通常 JavaScript 对象中的 setter 和 getter 方法遵循以下语法。创建的对象具有多个属性。 setter 方法有一个参数,而 getter 方法没有参数。两者都是函数。

对于已在对象内创建的给定属性,set 方法通常是一个 if/else 语句,用于在以后通过代码直接访问和分配该属性的任何时候验证输入,也称为“set”。这通常是通过使用 if (typeof [arg] === '某种类型的值,例如:数字、字符串或布尔值') 语句来完成的,然后代码块通常会分配 this.(specific)property-name到论点。 (偶尔会在控制台中记录一条消息。)但它不需要返回任何内容;它只是设置 this.specific-property 来评估参数。然而,else 语句几乎总是在控制台中记录一条(错误)消息,提示用户为满足 if 条件的属性键值输入不同的值。

getter 方法基本上是相反的。它设置一个不带任何参数的函数来“获取”,即当您调用刚刚设置的特定属性时返回一个(另一个)值/属性。它“得到”的东西与调用该对象属性时通常得到的东西不同。

对于您不希望能够直接修改的属性键值,可以轻松查看 setter 和 getter 的值,除非满足某些条件。对于这种类型的属性,使用下划线来处理属性名称,并使用 getter 来允许您能够调用不带下划线的属性。然后使用 setter 定义可以访问和分配属性的键值的条件,也称为“设置”。例如,我将为此对象的属性添加两个基本的 setter 和 getter。注意:我使用常量变量是因为对象保持可变(创建后)。

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;
}

};

有趣的是,当您尝试为 _age 属性设置/分配新的键值时,因为它必须满足 if 条件才能成功分配,这意味着并非所有分配都有效,等等。

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

请注意我是如何做的借助 getter 方法,能够通过 person.age 属性访问 person._age 属性。此外,与年龄的输入仅限于数字类似,名称属性的输入现在仅限/设置为字符串。

希望这有助于解决问题!
此外,还有更多链接:

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

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

囚我心虐我身 2024-11-01 09:03:38

根据 Mozilla 的说法,它们不在 ECMAScript 中。

According to Mozilla, they are not in ECMAScript.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文