Solving ugly syntax for getter in js

我怕爱的太早我们不能终老 提交于 2019-12-25 08:20:10

问题


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?


回答1:


You can't!

  • You can't override javascript operators or keywords.
  • you really can't have one operator\keyword that does two different things in the same context!



回答2:


Ok, had a play and it looks like this is "possible" (At least in chrome) but its a bit of a dirty hack.

var person = {
   _name: "John",
   name: function() {return this._name;},
}
person.name.toString = function(){ return person._name; }

Which will result in both person.name and person.name() returning "John".




回答3:


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:

  1. make a rule that you have to use the function to access the variable (yuck)
  2. 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"


来源:https://stackoverflow.com/questions/9777856/solving-ugly-syntax-for-getter-in-js

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