Author Topic: Access any javascript class variable with one function  (Read 1889 times)

0 Members and 1 Guest are viewing this topic.

Offline theKit

  • Devotee
  • **
  • Posts: 178
    • View Profile
Access any javascript class variable with one function
« on: November 26, 2014, 02:46:31 am »
I'm working on a little game and I have character objects that have a shit ton of variables in them and I need to access these but it seems like a waste to write a bunch of accessor functions like this:

Code: [Select]
character.prototype.getName = function(){
     return this.name
}

character.prototype.getAge = function(){
     return this.Age
}

ect

Is there a better way of going about this?


Offline crazzyass

  • Adherent
  • *
  • Posts: 97
    • View Profile
Re: Access any javascript class variable with one function
« Reply #1 on: November 26, 2014, 04:22:08 am »
I'm working on a little game and I have character objects that have a shit ton of variables in them and I need to access these but it seems like a waste to write a bunch of accessor functions like this:

Code: [Select]
character.prototype.getName = function(){
     return this.name
}

character.prototype.getAge = function(){
     return this.Age
}

ect

Is there a better way of going about this?

If there isn't, there should be. I'll think on it some.

There's likely a library or toolset that takes care of that already out there, I'm sure.

Offline LiquidIce

  • Adherent
  • *
  • Posts: 52
    • View Profile
Re: Access any javascript class variable with one function
« Reply #2 on: November 29, 2014, 01:41:51 pm »
If name is a property of that object, can't you just get it by running  "badGuy.name" or "badGuy['name']"?

Offline Lanny

  • Zealot
  • ****
  • Posts: 1,123
    • View Profile
Re: Access any javascript class variable with one function
« Reply #3 on: December 10, 2014, 03:14:02 am »
^that, nothing is private in JS so you can just just access the properties directly. But protos are just objects so you could add getters/setters programmatically if you want:

Code: [Select]
function buildProto(fields) {
  var proto = {}
  for (var i=0; i<fields.length; i++) {
    var name = fields[i], // so we're sure to capture "name"
      effName = (name[0]==="_")?name.substr(1):name //strip leading underscores

    // Capitalize first letter
    effName = effName[0].toLocaleUpperCase() + effName.substr(1)
   
    proto["get" + effName] = function() { return this[name] }
    proto["set" + effName] = function(x) { this[name] = x }
 }

  return proto
}

and that will do this:

Code: [Select]
>function Test() { this.foo = "bar" }
undefined
>Test.prototype = buildProto(["foo"])
Object {getFoo: function, setFoo: function}
>t = new Test()
Test {foo: "bar", getFoo: function, setFoo: function}
>t.getFoo()
"bar"
>t.setFoo(42)
undefined
>t.getFoo()
42

Offline theKit

  • Devotee
  • **
  • Posts: 178
    • View Profile
Re: Access any javascript class variable with one function
« Reply #4 on: December 10, 2014, 03:26:11 am »
Impressive. Javascript is truly versatile as fuck...

As to why I don't just access them directly obj->name or obj.name, I was told that is bad practice as it ends up fucking you on larger projects, not sure how but getters/setters must be a thing for a reason.

Offline Umbrella Corp

  • Arch Disciple
  • ***
  • Posts: 644
  • Skullfucker
    • View Profile
Re: Access any javascript class variable with one function
« Reply #5 on: December 10, 2014, 04:26:00 am »
Nerds
Butts of Assrape

Offline Lanny

  • Zealot
  • ****
  • Posts: 1,123
    • View Profile
Re: Access any javascript class variable with one function
« Reply #6 on: December 10, 2014, 05:05:38 am »
Impressive. Javascript is truly versatile as fuck...

Yup. It can bite you in the ass for sure, but for all the terrible things about JS it can be really fun sometimes.

Quote
As to why I don't just access them directly obj->name or obj.name, I was told that is bad practice as it ends up fucking you on larger projects, not sure how but getters/setters must be a thing for a reason.

That is... an opinion that some people hold and for which seemingly convincing arguments can me made. There is a long running clash of ideologies in programming and the whole getters/setters thing is one paradigmatic place where that gets played out. There's the notion of "information hiding" that's really near and dear to people in the OOP world. The classic example that's supposed to illustrate this point involves rectangles (other shapes will do, but area is easy for rectangles):

Code: [Select]
function Rectangle(width, height) {
  this.width = width
  this.height = height
}

Rectangle.prototype = {
  getWidth: function() { return this.width },
  getHeight: function() { return this.height },
  getArea: function() { return this.width * this.height }
}

function CachedRectangle(width, height) {
  this.width = width
  this.height = height
  this.area = width * height
}

CachedRectangle.prototype = {
  getWidth: function() { return this.width },
  getHeight: function() { return this.height },
  getArea: function() { return this.area }
}

The notion here is that an instance of Rectangle can be substituted for CachedRectangle with no changes to any code so long as the getters are the only thing that's being used. This is a hedge which is supposed to save you programmer time if you decide that it's better to precompute area or whatever. And the example works, if you're using properties directly you really couldn't substitute one for the other without issue (well actually with ES6 you could, but being charitable (and practical, for the immediate future) that's irrelevant).

I'm not really a fan of the philosophy that informs people making this argument. I think this is a pretty example but in my experience at least (and it seems like others have the same experience) there is a tremendously greater amount of effort spent on other things like managing mutable state or concurrency issues than there is on swapping out implementations of equivalent abstract data types. In fact I'd argue more time is actually spent in writing these dumb getter/setter methods than is saved by them.

I'm pretty opinionated on the subject though, and it's worthing noting that the OOP approach (in favor of getters/setters on everything) is more popular today (in terms of numbers) than competing views. I think the important takeaway is that you should assess the situation for yourself, there is a strong enough argument for either position that which ever way you think is best, so long as it's based on evidence, is justifiable.

Nerds

u jelly JELLYFISH.JPG

Offline SBTlauien

  • Disciple
  • ***
  • Posts: 454
  • ส็็็็็็็็็.ส็็็็็็็็็.ส็็็็็็็็็
    • View Profile
Re: Access any javascript class variable with one function
« Reply #7 on: December 11, 2014, 02:54:32 am »
I've gotten in a habit of using them in JAVA even though I've noticed that I could just make the variable public and access it directly.  I always figured they are more for security on the server side(like JSP and JavaScript on the server side).

Offline aldra

  • Arch Disciple
  • ***
  • Posts: 623
  • albrecht drais
    • View Profile
Re: Access any javascript class variable with one function
« Reply #8 on: December 11, 2014, 03:01:34 am »

That is... an opinion that some people hold and for which seemingly convincing arguments can me made. There is a long running clash of ideologies in programming and the whole getters/setters thing is one paradigmatic place where that gets played out. There's the notion of "information hiding" that's really near and dear to people in the OOP world. The classic example that's supposed to illustrate this point involves rectangles (other shapes will do, but area is easy for rectangles):

not specific to OO, I like the concept of having standardised functions to update common files/variables/objects because if I need to change the structure of the data, I only need to make changes in one place as opposed to all over the code. it's not mandatory or anything but it's a good idea.

Offline Lanny

  • Zealot
  • ****
  • Posts: 1,123
    • View Profile
Re: Access any javascript class variable with one function
« Reply #9 on: December 11, 2014, 06:53:10 am »
not specific to OO, I like the concept of having standardised functions to update common files/variables/objects because if I need to change the structure of the data, I only need to make changes in one place as opposed to all over the code. it's not mandatory or anything but it's a good idea.

Sure, sure, separating what from how as important in FP as OO. I mean that was even a big lesson of structured programming. But there's a certain trend towards this rigid kind of runtime enforced access restriction that flows forth from the Java world and informs most of what we call OOP today that goes a lot further than that. Like some things really are just fields, and you're never going to need to inject code into accessing them. I think there's also this risk of expanding access methods to do more than they should.

Like I was reading this dude's code the other day and he had this setter that just did your normal set but then it checked the value afterwards and if it met a certain condition it would call something else and there's be this big call chain and the state of the whole program is up in the air when you're just trying to set one field. It gets to a point where enough information is hidden from you that you can't reason about how a program works anymore. Which is to say, that example was a bad design to start with and most OOP people could tell you that, but I think having those dumb getter/setters laying everywhere makes it much easier to make that mistake than if you were just passing around a value or something.

Offline aldra

  • Arch Disciple
  • ***
  • Posts: 623
  • albrecht drais
    • View Profile
Re: Access any javascript class variable with one function
« Reply #10 on: December 11, 2014, 11:53:20 am »
haha wow, I can understand what you mean but I've never seen anyone quite do that.

then again, I don't generally have to work with other peoples' code so I guess I'm kinda shielded.