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');
Related
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.
I wonder if it's possible to give a a type/class to JavaScript functions.
Of course, the Object class/type of function is 'Function/function'.
http://bonsaiden.github.io/JavaScript-Garden/#types.typeof
However, in my project, somehow I want to define class for function to group them.
It's similar concept HTML/CSS DOM element class.
I have a function which args is a function, and I want to distinguish which type or class of function is passed to the function.
It does not work with any object method, just a function, but it can be distinguished like obj.hasOwnProperty('someClass') .
I just wonder if there's smart way, if you think impossible, please insist so.
Thanks.
PS. I do not why someone vote -1 and to close this question.
This is the matter of reflection of Javascript. It's ok if find some reflection factor of JS is limited. and I think it's not wise to avoid to make it clear that something is impossible in a certain language.
A function is an object. You can add your own custom properties to any function. So, if you want to set your own type on several different functions so you can test for that, you can just add the same custom property (with different values assigned to it) to each of those functions.
function myFunc1() {}
myFunc1.myType = "whatever1";
function myFunc2() {}
myFunc2.myType = "whatever2";
function myFunc3() {}
myFunc3.myType = "whatever3";
function callMe(cb) {
if (cb.myType === "whatever1") {
// code here
} else if (...) {
// code here
}
}
callMe(myFunc1);
Note, this is a bit unusual and if you explained the actual problem you were trying to solve, there is probably a more common design pattern that might help you.
#jfriend00 has suggested the answer.
FYI, functions are objects so they can have your own custom properties so you could make your own custom property.
He's right, so to add a class/property to any functions, simply do
var myFunction = function(foo){...};
myFunction['someClass'] = true;
//To distinguish
if (someFunction.hasOwnProperty('someClass'))
{
console.log('someFunction is someClass');
}
This is a general question about best practice in jQuery syntax/code organisation.
Consider the following snippet, used in a jQuery AJAX function:
if(obj.status == "error"){
$("#alert").html(obj.message);
}
I have also seen this written as:
function alert_box(str)
{
var html_str = '';
$("#alert").html(html_str);
}
if(obj.status == "error"){
alert_box(obj.message);
}
Functionally, this is precisely the same. My question: Is there any semantic or practical reason for differentiating between the two? What about load time / performance issues?
This is seems to be a question of "why use functions in general"? The idea behind a function is that you're making a code block reusable without having to write out the same code again. If you want to do that same thing in several places throughout your script, the function makes sense. If you only do that once, it may not be as practical. Then again, functions also help you hide details where you don't care about them - so you can summarize an action while the details of that action are somewhere in that function definition.
In this specific case, that function is broken anyway. Rather than using the passed in argument str, you have an empty variable html_str that you're replacing the html contents of an element with. Also, there's no need here to use html rather than text, which is better performance.
function alert_box(str) {
$("#alert").text(str);
}
Even though this is only a one liner, this can still be practical because it would let you use alert_box in several places throughout the script and not have to change those places later if you decide to change what alert_box does. Even something like changing the id of the element would require changes in several places, for example.
It also worth noting that this function searches the DOM for "#alert" each time it runs. It would be most optimal to cache that reference like this:
$alert = $("#alert");
function alert_box(str) {
$alert.text(str);
}
A few things that are great to study:
KISS
DRY
SOLID aka OOP
Excuse me first. because i don't know this is question is valid or not. i if any one clear my doubt then i am happy.
Basically : what is the different between calling a method like:
object.methodname();
$('#element').methodname();
calling both way is working, but what is the different between, in which criteria make first and second type of methods. is it available in the core javascript as well?
In case if i have a function is it possible to make 2 type of method call always?
Can any one give some good reference to understand correctly?
Thanks in advance.
The first syntax:
object.methodName();
Says to call a function, methodName(), that is defined as a property of object.
The second syntax:
$('#element').methodname();
Says to call a function called $() which (in order for this to work) must return an object and then call methodname() on that returned object.
You said that "calling both way is working," - so presumably you've got some code something like this:
var myObject = $('#element');
myObject.methodname();
This concept of storing the result of the $() function in a variable is commonly called "caching" the jQuery object, and is more efficient if you plan to call a lot of methods on that object because every time you call the jQuery $() function it creates another jQuery object.
"Is it available in the core javascript as well?" Yes, if you implement functions that return objects. That is, JS supports this (it would have to, since jQuery is just a JS library) but it doesn't happen automatically, you have to write appropriate function code. For example:
function getObject() {
return {
myMethod1 : function() { alert("myMethod1"); return this; },
myMethod2 : function() { alert("myMethod2"); return this; }
};
}
getObject().myMethod1().myMethod2();
In my opinion explaining this concept in more depth is beyond the scope of a Stack Overflow answer - you need to read some JavaScript tutorials. MDN's Working With Objects article is a good place to start once you have learned the JS fundamentals (it could be argued that working with objects is a JS fundamental, but obviously I mean even more fundamental stuff than that).
The difference is very subtle.
object.methodname();
This is when JavaScript has the object at hand.
$('#element').methodname();
If you are using jQuery, you are asking jQuery to select the object that has the id of #element. After that you invoke the method on the selected object.
A few days ago, I asked a question regarding dynamically modifying a function's code midway through the outerlying script's execution and I was told to completely forget ever coming upon the notion. I'm not sure I understand why that is. Let me give an example:
<script>
var display = function(msg)
{
alert(msg);
}
// Now, at the moment, the display() function
// is receiving a single parameter and alerting
// it to the user. I'm now going to use eval()
// to modify the display() function.
eval('display = ' + display.toString().replace('alert(', 'document.write('));
// Now, the display() function writes its parameter
// to the document as opposed to alerting it.
</script>
I realize this is a rather trivial example, but there must surely be some use that can be derived from being able to dynamically modify a function, something so useful by itself.
Although this may do what you need it to do, 6 months from now you (or the person maintaining your code) will be going "WTF?!"
If your use case is to alert or write based on some condition, why don't you write two different functions? Or have your function take another parameter that decides the output mode. Or pass in a function as a parameter that performs the actual output. Something, you know, a little more on the sane side. ;-)
There are cases where it could be useful to change a function's behavior, but there are better ways to do it. In your example, you could create new instances of the function that handle the output differently, by passing a function as an argument (similar to the strategy pattern):
function makeDisplay(displayStrategy) {
return function(msg) {
// I'm assuming you would do some additional processing here...
displayStrategy(msg);
}
}
var display = makeDisplay(alert);
// now modify display to use document.write
display = makeDisplay(function(msg) { document.write(msg); });
Well, using eval might be a security concern but modifying a function in real-time is ok. How else you can make memoization anyway?
Although, come to think of it, changing method signature isn't a great idea, other people won't know how to call this function after this, since it would depend on execution order and it's not easy to track usually.
I have found myself needing to do this in situations where I don't have the source code for a particular piece of vendor javascript; so that could be a legitimate use case. I agree that if you have another option, it's better to do it in a more organised way, editing the original function to be more flexible.