在js中解决getter的丑陋语法 [英] Solving ugly syntax for getter in js
问题描述
让我们使用这个对象:
var person = {
_name:John,
name:function(){return _name}
}
<
myTextBox.value = person.name()
将返回
John
pre>
但
myTextBox.value = person.name
将返回
function(){return _name}
如何强制两个语法返回John
?我可以在这里使用封闭(我之前问过的问题)吗?解决方案如果您只支持现代浏览器,则可以使用 ES5 Getters ,但一般来说,这是
您的选择是:
- 制定规则,您必须使用该函数来访问变量(yuck)
- 不要担心。
我会去#2。
我想你在这里的语法感到困惑,与现在相同的问题:
function Person(name){
this._name = name;
}
Person.prototype.name = function(name){
if(name)this._name = name;
return this._name;
}
var j = new Person(Jay);
j.name()//Jay
j.name(Thomas); //我可以设置值
j.name()//Thomas
似乎您正在尝试创建真实的私有变量,这是可能的,但可能没有帮助。
function Person(name){
var myName = name; // private
this.name = function(){
return myName;
}
}
var j = new Person(Jay);
j.name(); //仍然必须使用perens
最后,因为你的只是一个简单的对象,我们可以这样做。不确定为什么你想要:
var person = {};
(function(name){
var myName = name; // myName和name,都是private的,但是没有帮助
person = {
name = myName
}
}(Jay))
person.name //Jay
Let's take this object:
var person = { _name: "John", name: function() {return _name} }
In GUI,
myTextBox.value = person.name()
will return
"John"
But
myTextBox.value = person.name
will return
function() {return _name}
How can I force both syntax to return
"John"
? Could I use a closure (question I asked previously) somehow here?解决方案If you support only modern browsers you can use a ES5 Getters, but in general this is JavaScript, why are you trying to make it complicated?
Your alternatives are:
- make a rule that you have to use the function to access the variable (yuck)
- don't worry about it.
I'd go for #2.
I think you're getting confused with this syntax here, but actually it has the same problem as you do now:
function Person(name) { this._name = name; } Person.prototype.name = function(name) { if (name) this._name = name; return this._name; } var j = new Person("Jay"); j.name() // "Jay" j.name("Thomas"); // I can set the value as well j.name() // "Thomas"
It seems like you're trying to create real private variables, which are possible, but probably not that helpful.
function Person(name) { var myName = name; // private this.name = function() { return myName; } } var j = new Person("Jay"); j.name(); // still had to use perens
Finally because yours is just a simple object, we can do this. Not sure why you'd want to though:
var person = {}; (function(name) { var myName = name; // myName and name, both private, but not helpful person = { name = myName } }("Jay")) person.name // "Jay"
这篇关于在js中解决getter的丑陋语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!