Node.js binding to a method from a string - javascript

I'm not expert at all in Javascript and node.js
If I want to access to a method that is contained into a string, What should I do?
Is that possible?
For instance:
function bindJS(method, path){
var js = require(path+".js");
}
and the method I'd like to get is: js.what's_inside_method
Any idea how to do that?
Thanks!

Is method a property of js? Can you use js[method]()?

The only way to do this is with eval which is potentially unsafe if your data comes from a non-trusted source (unless it's hard-coded into the code, it's an untrusted source). So, lots of red flags, but this should work:
function bindJS(method, path){
var js = require(path+".js");
func = eval(method);
func();
}

Related

Is it possible to define a new statement?

I want to be able to define a statement in javascript. For example, I want to define
a statement called file that works like a class.
function file() {
//code goes here
}
I want that to be used as a statement, like if,for,andreturn.
file filename(filename,purpose) {
//code goes here
}
Do I need to build a seperate compiler or is it possible?
Please change the title if there is a better way to say it.
What are you trying to accomplish?
You can emulate some class-like structure in JavaScript using the Revealing Module Pattern
Also, I've never seen a class work like what you've described -- typically you instantiate an object of a class, and then access the object's public properties. This can be done in JavaScript ('cept objects are created dynamically). For example:
// file 'class'
var file = function () {
var a; // private variable
function filename(name, purpose) {
// code goes here
}
// return public members
return {
filename: filename
};
};
// An object created from your 'class' with the member function 'filename()'
var aFile = file();
Then call your member function using the . operator, like so: aFile.filename(name, purpose);
This would be writing a new language based on Javascript, much like Coffeescript, among many others. Those languages need to compile to JS before being served to a web browser, for instance.
Take a look at a Coffeescript -> JS interpreter to know how to go about this. For the record, I don't think this is a good approach.
Lastly I'll note that languages like Scala have very good DSL support, meaning it's easy to add features within the language. For instance, even + in Scala is library code, not native code. (More technically, could be written that way from a language standpoint.)
I want to be able to define a statement in javascript.
I want that to be used as a statement, like if,for,andreturn.
No, you cannot do this, as a Javascript parser would not be able to parse this.
If you really wish to do this, your only option would be to create your own language, and write a transpiler from your new language to Javascript, as #djechlin has pointed out.
I believe what you want is to implement control structures rather than statements since the example you gave, if, for and return are control structures. If that is what you really mean then yes, you can do that with functions but not with the syntax you describe.
In javascript, functions are first class objects. That is, they can be assigned to variables and passed as arguments to other functions. For example, here's an implementation of if that uses no built-in control structure (no if, while, switch etc. and no ternary operator):
function IF (condition, callback) {
[function(){}, callback][+!!condition]();
}
You can use the above function as a replacement of if but the syntax is a bit unconventional:
IF ( a == b, function(){
console.log('hello');
});
But if you've been programming javascript long enough the above syntax would be familiar and you'd have encountered many similar control structures implemented as functions such as [].forEach() and setTimeout().
So, if you want to implement a control structure to parse a file for example, you can do something like this:
function parseFile (filename, callback) {
// code to process filename
callback(result);
}
Or even something like this:
function eachLine (filename, callback) {
// code to process filename
for (var i=0; i<file_content.length; i++) {
callback(file_content[i]);
}
}
which you can use like this:
eachLine("some_file.txt",function(line){
if (line.match(/hello/)) {
console.log('Found hello! This file is friendly.');
}
});
if you don't need parameters you can do:
Object.defineProperty(window, 'newcmd', {
get: () => console.log("hello")
})
newcmd

Embed variables in very simple javascript function

Hi for some reason I can't get this function to work.
function go(type)
{
location=document.category.example.options[document.category.example.selectedIndex].value
}
All i want to do is embed the type variable, the go function becomes undefined whenever I try to do something like
location=document.'+type+'.example.options[document.'+type+'.example.selectedIndex].value
What am I doing wrong?
instead of document.'+type+'.example.options[document.'+type+'.example.selectedIndex].value you should write:
document[type].example.options[document[type].example.selectedIndex].value
You can use document[type].example
You need to learn more about JavaScript syntax before you do stuff like that.
Here is a solution to your problem:
function go(type)
{
location=document[type].example.options[document[type].example.selectedIndex].value;
}
go('category');
It takes advantage of the fact that these two are equivalent:
a.b === a['b']
But obviously in the second part, b can be replaced dynamically since it is a string.

What is the correct way to "serialize" functions in javascript for later use

I have a "library" of objects that I want to load on the fly from a database. Each object comes with its own special functions that are called at specific times depending on the objects type. Ideally I'd like to be able to do this, although its been pointed out that this doesn't work:
library = {
"myObj" : {"name" : "myObj", "type" : "myType", "function" : function () { } } //, etc
}
The string "myObj" is passed around my program quite a bit, but I only have to access certain values of the object at a time, and in some circumstances there's a specific function that needs to be run. The problem is that I'm looking at hundreds, and eventually thousands, of potential objects that could exist with varying functions.
What is the "right" way to store a function to be called like this. I know that calling eval can be very unsafe during execution, enabling xss attacks and whatnot. I really want to avoid a massive switch statement or the bloated loading of additional functions. I'd also like the solution to be as concise as possible.
This can't be the first time this has come up. ;/
Thanks for your help.
Just use eval to recreate the function after loading it as a string. So if you deserialize an object myObj from JSON, and you have a property:
myObj = {
....
function: "function() { ... }"
}
you can very easily turn it to a real function:
eval("myObj.func = " + myObj.func);
http://jsfiddle.net/kceTr/
Oh - I am not sure if that was an edit or I missed it before - but re: eval.
Eval is a tool. You want to store a function in a database. It really doesn't make much difference if you have to "eval" to turn it into code, or there was some other magic way to do it: if someone can change the data in your DB, then they can change a function.
If you need to store a function, then eval is your tool. It's not "bad" by nature, it's bad because it's easy to misuse. Whether you use it well or not is up to you.
Remember anything running on the client is still just running on the client. There's nothing a malicious person could do with eval, that they couldn't do with the Chrome debugger a lot more easily. Anyone can always run any code they want on the client, it's up to your server to decide how to handle what it receives. There's nothing safe on the client in the first place...
Changing the prototype of the object is a half thought I have.
You've got your library like
library = {
"myObj" : {"name" : "myObj", "type" : "myType", "function" : function () { } } //, etc
}
You've got an object (let's call it theObj) that you know is a myObj (due to a string maybe? property?)
theObj.__proto__ = library["myObj"];
That way you can execute
theObj.function(...);
jsfiddle example (it's rough!). Also, be careful with proto, it's deprecated (1) (2)
As to serializing the functions, can you get them in using a script tag that points to something serverside that slurps them from the db and returns the js? Just include them inline as you render the page (in a script block)? Or, if all else fails, eval should work, as long as you know that the functions you've got stored in the database are clean and safe.
There is no right way to do this, because its not generally a good idea.
HOWEVER, if you want to do it anyways you can simply extend the prototype of Function with a .toJSON method.
Function.prototype.toJSON = function(){ return this.toString(); }
Then you can simply use JSON.stringify and functions will be serialized as strings.
Its generally a not good idea in most cases. There are very few circumstances where you want to do this and even then, there is probably a better way.
A better approach might be to serialize the object's properties when you "sleep" it, and "waking" the object by reattaching its properties to a new instance of the object with the appropriate methods defined.
what you are doing with it is just fine. However, if i were you, for readability and tidyness, i would rather have the function created outside and simply have it assigned to your object key.
You don't need eval here. Instead do it this way whenever you want access to the stored function -
library.myObj.function()
You do your best in parameterising your functions, so that you end up
with as little typologies as possible.
Store them on the server in individual JS files, then load the needed file dynamically, by name.
In the JSON, only store the name of the file that contains the function that you need. And, of course, you will be caching already loaded files, to go easy on the server.
Just my two cents.
You can only really serialise a whole file with require calls in it. If you do that, you can create a module, exports and module.exports, eval the file with a function surrounding it and snag the module.exports out of it.
It's not exactly secure, but for that you need to use something like VM2 and value-censorship (which I've been working on) to avoid them calling eval() and owning your machine or the entire network.

Javascript: Is it possible to have a function that is automatically fired when an Object/String... created?

the question is straight forward. Just like in PHP we have the magic function __construct(), is there any related function or hack I can use in javascript?
Example:
function setLength() {
/* Some work */
}
var a = new Object();
b = new String("Hello");
//Is there anyway the function setLength() will automatically be fired when an Object or String... created?
I'm looking forward to your answers. Thank a lot for any help.
[x]
Trying to overload String would be a bad idea, especially if working with third party libraries. Same would go for augmenting Object.
However, here is how you may do it, but I don't recommend it..
var _String = String;
window.String = function() {
setLength();
return new _String(arguments[0]);
}
This obviously won't be called when creating a primitive string too.
jsFiddle.
You could use a string factory function that returns a new String object and calls your function.
var stringFactory = function(chars) {
setLength();
return new String(chars);
}
This has some advantages, mainly the String constructor is not overloaded.
You can just create your own object by doing something like this. The function acts as the constructor:
$(document).ready(function(){
var instance = new object('test123');
alert('Instance: '+instance.len);
function object(var1){
this.var1 = var1;
this.len = this.var1.length;
}
});
You can override string.prototype.constructor to alter the default functionality of the string constructor, and object.prototype.constructor to alter the default functionality of the object constructor.
However, overriding the default functionality of JavaScript's core classes is widely considered to be bad practice, and there is likely a better way to accomplish your end goal.
If you do decide to do this, you might also benefit from reading the following SO Post about overriding a function with a function that references the overridden function: Overriding a JavaScript function while referencing the original
After messing around with jsFiddle, and then doing some research. I found out that I'm actually wrong. String primitives are immutable, so you can't override the constructor, as I suggested. Check out String prototype modifying itself, for more info on that.

how to return multiple values from NPAPI plugin method to javascript

To my knowledge, the NPAPI plugin methods return only the NPVariant *result.
But i need a multiple strings and integers that are passed to the plugin method as parameters, modified inside the plugin method and then their modified value is used in the javascript that is calling this plugin method.
Can i get some help regarding this matter?
Is it the case that only the value that is returned by the method can be used in javascript or we just need the variable type to be NPVariant for it to be usable in the javascript without the plugin method returning it.
in js, you return multiple value by array or object (afaik, they are pretty much the same.) and I guess you just need the same technique for npapi plugin, i.e. create a object, do what ever you want (add what ever field you need in it), and return it.
I think you can also use the similar way to simulate the fallowing js code
function (obj) {
obj.n = 2;
obj.strs[0] = '';
obj.strs[1] = 'a';
}
(sure you need to check the type of obj etc.)
(basically my point is you just need to simulate what you can do in js~~)
(haven't try myself, tell me if I am wrong)

Categories

Resources