JavaScript中的获取器和设置器(正确的语法?) [英] Getters and Setters in JavaScript (Correct syntax ?)
问题描述
我是JavaScript的新手,但通常对OOP都不是.
I am new to JavaScript, but not to OOP in general.
这是创建吸气剂的有效方法吗? JavaScript中的二传手?
Is this a valid way of creating getters & setters in JavaScript?
类",
function Person (age){
this.age = age;
};
Getter,
Person.prototype.getAge = function(){
return this.age;
};
和二传手.
Person.prototype.setAge = function(arg){
this.age = arg;
};
它似乎工作正常,但我不知道约定,我到处都有不同的描述,但是我的解决方案有效吗?
It seems to work fine, but I dont know the convention, I get diffrent descriptions everywhere, but is my solution valid?
推荐答案
You probably want Object.defineProperty
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), here's an example of it in use:
Object.defineProperty(Person.prototype, 'age', {
get: function(){
return this.__age__;
},
set: function(value){
this.__age__ = value;
}
});
如果需要,还可以在其他位置保存变量.以下内容将作为在Person
的所有实例中设置和访问的单例值:
You can also hold a variable somewhere else if you want. The following would act as a singleton value that is set and accessed across all instances of Person
:
var age;
Object.defineProperty(Person.prototype, 'age', {
get: function(){
return age;
},
set: function(value){
age = value;
}
});
如果要为创建的Person对象的每个实例提供age
变量,则需要在构造函数中添加变量声明:
If you want an age
variable for every instance of the Person objects you create, you need to add the variable declaration inside your constructor:
function Person(){
var age;
// ditto from the second example
}
这篇关于JavaScript中的获取器和设置器(正确的语法?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!