Reflection in Node.js - javascript

anyone know how to use Reflection in Node.js/Discord I want to replace
my direct map property call:
Userlist.get(uid).Strength
with a more programic one like
var DamangeStateName = "Strength"
Userlist.get(uid).DamangeStateName
which would get the Strength property like the direct one.
The main reason I need reflection is because sometimes the Key attribute is "Agilty" not "Strength"
And while my code everwhere else works with the string variable my Map of the player data can't use those same tricks and i need to be able to use reflection os it synergies with the rest of my code

JavaScript, being a prototype-based language where everything is basically just a hashtable of strings to values, neither has nor needs reflection machinery in the sense that Java or C# have.
I think you want something like this:
Userlist.get(uid)[DamangeStateName]

I believe you don't need reflection for your stated problem. You want to be able to handle two keys that mean the same thing.
Extend the target item (object/class) with a method to wrap the logic.
Userlist.get(uid).DamangeStateName
User.prototype.NormalizedDamangeStateName = function() { /* ... */ }
My User is an assumption. You'll need to identify the correct object by determining what Userlist.get(...) returns... Regardless, the concept should be sound.

Related

JavaScript/TypeScript equilavant of PHP's magic ::class constant

PHP has some build-in magic constants, one of which is ::class. Since I am building more and more applications with NodeJS + TypeScript I wondered what the JavaScript/TypeScript equivalent is of the following PHP code
$callable = array( Foo::class, 'method' );
call_user_func( $callable );
I tried using the following, but that is obviously not a correct array value
const callable = [Foo.constructor.name, 'method']
And how can I then call the method?
In PHP symbols are not values in the same way they are in JS. We can't pass around classes in PHP, only their names. This works in PHP because class names are globally unique (namespace included).
In Javascript classes are 'first class', and disconnected from their name. They are not globally unique. So the premise doesn't make that much sense to me. You shouldn't pass around just the name, because with the name alone you cannot figure out what class it was.
However, here are some things that resemble what you need.
If we look at the [class, staticMethod] structure as a single value that you want to be able to call, then the easiest is to use:
const callable = Foo.method;
// callable
callable();
This is so natural in Javascript. In PHP the array syntax for referencing things that are callable is a bit of a hack, so it's not really the model you'll want to replicate.
If, for some reason, you want to have a value that has the method name and a reference to it's class, you don't need to do this by name (which aren't globally unique), do it by reference.
const callable = [Foo, 'method'];
// Call it:
callable[0][callable[1]]();
It's tempting going into a new language to re-use the patterns that you are used to from your old one; but Javascript model is significantly different. Whatever you're actually trying to achieve probably has a solution that's more natural to JS.

Manipulating X and Y Properties Unity2D-Javascript

I'm new to Unity and Javascript, both of which I'm using for my new project, and my question is this: why must it be so difficult to simply access and manipulate x and y values? My whole life I've used AS for Flash and recall better days, when one could simply
trace(mc.x);
and
mc.x++;
But from the research I've done it seems that one can't even access a Game Object without typing out a tedious
GameObject.Find("mc")
And that's just for accessing the Object! As far as finding the object's position or for even moving an object to a point, I have no idea. I tried finding the answer online, but couldn't find anything.
And yes I understand that one can add to an object's position through
GameObject.Find("mc").transform.Translate(1,0,0);
But even that seems clumsy compared to the AS equivalent of a simple
mc.x++;
Thank you for your time.
It sounds like maybe you need to learn more about components. Any public GameObject field in your script classes (as long as they extend Component, or even better MonoBehaviour) can be filled with a reference to another GameObject by dragging and dropping the object in the Inspector pane. You can then reference the variable like normal.
GameObjects by themselves are not particularly useful, but you can use GetComponent() to find parts you need on those objects -- like Transform, Renderer, Rigidbody, or your own Component classes. You can also create public fields that have the specific Component sub-type you need, and reference them directly.
For example:
var anObject : GameObject;
var aTransform : Transform;
function Start(){
if(anObject != null)
Debug.Log("I know about an object called " + anObject.name);
if(aTransform != null)
Debug.Log("I know about a transform at " + aTransform.position);
}
As a side note - GameObject.Find() is really slow! If you use it too much your game will not perform well.

JS - Call function by name (in object notation)

I want to clean up some old code and optimize it, which often uses the same code. (with only different names of functions to call)
I make a easier example and no, I don't write on a game. But this example looks more comprehensible to explaination of my issue.
character.sleep(1);
character.changeName(name);
character.useItm(1423);
Easier Example:
object.function(parameters)
Target was something like this:
myFunc(funcName,value) {
character.{funcName}(value);
}
$('.btn_sleep') { myfunc('sleep','1'); }
$('.btn_cName') { myfunc('changeName','Harold'); }
$('.btn_uItem') { myfunc('useItem','1423'); }
First I thought about to use eval(), because no user-input will come near of this functions. But I dislike this idea because of the performance lost.
Then I looked around for alternatives and found window[] and new function() as solution.
But I dont get an idea how to use it, when I want to dynamcially call a function by name in an object-notation. (Or in worser cases, when you've to get the result for an if-condtion from a function, which you called with object-notation.)
Could anyone help?
The best way I know how to dynamically call functions is using bracket notation because it allows you to set your object path with a variable
function myFunc(funcName,value) {
character[funcName](value);
}
myfunc('sleep','1');

When should I use data type classes in JavaScript

I come from a C# background. I've been working a lot with JavaScript lately. On a new app, I have a mysql/php back end. I'm going to be passing a lot of "types" back and forth.
So in my data base, I have several tables like
table1
id, fieldx,fieldy,fieldz
table2
id, fielda,fieldb,fielc
In c# I would definitely write classes for all those in the code. Which led me to implement things like so (in my JavaScript app):
function table1(id, x,y,z){
this.id=id;
this.x=x;
this.y=y;
this.z=z;
}
After about 6 tables worth of that, it suddenly occurred to me that maybe there was no point at all in making these classes.
So my question is, in a JavaScript app, do I use "classes" for data types? or should I just "document" which fields/types are expected and so in the code instead of
a.push(new table1(5,1,2,3));
I would just have
a.push({id:5,x:1,y:2,z:3});
This may seem like a preferences question but it's a fundamental language question that I have as I try to understand how to model my app's data in JavaScript. Is there any advantage of the classes (with only data fields) or is it just a mistake. Thanks.
It depends,
Note: Most of the programmers coming from a strong OO language will have trouble like you in regard to JavaScript's functional behavior (you are not alone).
If you want to create something closer to C# I would do the following:
function Table1(id, x, y, z) {
this.id=id;
this.x=x;
this.y=y;
this.z=z;
}
Table1.prototype.mySpecialTable1Method= function()
{
console.log(this.id);
};
Implementation:
var t = new Table1(1, 2, 3, 4);
t.mySpecialTable1Method();// outputs: 1
If you need to have methods that interact with the (soon to be) objects then I would definitely go with the code above. In addition it will make it clear when working with the objects that are related to a specific 'type' (naming the data).
But if your objects do not require any special "treatment" then I don't see any problem to use normal js object literals and pass them along (probably good for small projects).
Something along the lines:
var table1 = {};
table1.id = 1;
table1.x = 2;
table1.y = 3;
table1.z = 4;
console.log(table1.id); //outputs: 1
Extra reference:
http://www.youtube.com/watch?v=PMfcsYzj-9M
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Update:
For the sake of readability and scalability and the point that you are coming from C# you may want to stick to the "class" implementation just because it will define the correlation between the raw data and the objects you are working with.
There is a good chance that you are going to work with some data that will probably be messy and unorganized.
MVC may be the solution for you. It tries to bring some order to the chaos that you are expecting. I recommend to check out some of them like: AngularJS or Ember.
Another solution may be reactive js - but mostly if you are going to interact with the DOM according to your data (ReactJS, and Facebook's React as some good ones).
As a note for security, I would like to add that mapping the data closely to the db isn't a best practice but its your call.
Javascript is a funny language, and there are plenty of ways to do things. An Object is an Object in Javascript with or without a name. {} is just a short-hand way to create one.
If you are going for readability, then your initial example would be the way to go.
If you just want to get the block of data into an array, then your second example is appropriate. Personally, I would use your later example if it is just data.
If you are using functions and what not as well as data storage, and plan on reusing it several times in your code, then yes, define your object and call it appropriately.
JavaScript has no classes, it is a functional language and a function is a first class citizen in js meaning that a function is an object.
From your example I can see that your intention for classes is simply to pass data and using json is perfect for this.

Replacing a native Object (Array) method with a custom method: Is it safe? Compatible?

I've got an array, and it's got a method I threw onto it called add, which I use as a wrapper around push. I've found myself using push a few times when I should have used add, and now I'm thinking it would be nice to assign a reference to my add method to the array's native push. Thus, calling push on the array would call add.
Do internals depend on externally available native methods like push? How would this affect compatibility? Is this a bad idea? If so, why?
Some code:
PR.state = {
views: []
};
_.extend(PR.state.views, {
add: function(view) {
var parent = view.parent;
if ((!this.length && view instanceof PR.Views.App) || (parent && _.contains(this, parent)))
this.push(view);
}
});
// I am thinking:
PR.state.views.push = PR.state.views.add;
I would strongly advise against changing the behavior of a standard array method. If you really want a custom method, then just create a new method and give it it's own unique name and use that.
Changing the behavior of existing methods could have all sorts of bad consequences:
Incompatibility with code retrieved from any other source.
Creates a non-standard and unexpected implementation if anybody else ever works on this project. This is like adding in a time bomb to trip up some future developer.
Training yourself to use your own custom method instead of .push() is just something that a decent developer would do. Just do it.
Creating a newly named method with an appropriate and descriptive name improves the readability, understandability and maintainability of your code. Replacing an existing method with something that works differently does the opposite.
It's not so bad if you just replace the method on one instance of an array, not the whole array prototype, but it's still not a good idea.
What a stupid question. If I replace push with add, then what happens when I call push from add? :< :< I haven't tested it, but I suspect that while Array.prototype.push will still be available, unless I use Array.prototype.push explicitly, calling add will result in a mondo endless loop.

Categories