Use p5.js functions inside global variables - javascript

I want to have a file with global variables, for example:
function Globals() {
}
Globals.gravity = createVector(0, -9.81);
Unfortunately p5.js functions can only be used when they are declared inside setup() or draw() or are called from one of these functions.
My question is what would be the best approach to make globals easy to use?
My only idea is to make them functions, but that is not very pretty (you have to call function to get a value) and it is probably slow, because each access to a global variable requires making a call.
Globals.gravity = function() { return createVector(0, -9.81); }

Well, fortunately, you could use p5.js functions outside setup() and draw() function.
In order to use those functions, you need to call new p5() beforehand, like so ...
new p5(); //<-- call this
function Globals() {}
Globals.gravity = createVector(0, -9.81);
For more info, refer here

Related

How can I use createVector in a prototype?

function Childclass(){
this.printX = function(){
print(this.vector.y);
}
}
function Superclass(){
this.vector = createVector(1,2);
}
Childclass.prototype = new Superclass();
When running printX() I get the following error:
Uncaught ReferenceError: createVector is not defined
at new Superclass
Is this possible using createVector() in prototypes?
From the p5 FAQ:
Why can't I assign variables using p5 functions and variables before setup()?
Well, technically, you can by using on-demand global mode. But that's a less common use of p5, so we'll explain that later and talk about the more common case first. In regular global mode, p5 variable and function names are not available outside setup(), draw(), mousePressed(), etc. (Except in the case where they are placed inside functions that are called by one of these methods.) What this means is that when declaring variables before setup(), you will need to assign them values inside setup() if you wish to use p5 functions.
The solution itself is also in the FAQ:
We mentioned on-demand global mode earlier. This mode is most useful when you're building a program that uses other libraries and you want to control how p5 is loaded on the page with the others. You can read more about it here. But another interesting use of on-demand global mode is the ability to call p5 explicitly and then use p5 functions outside of setup(). Here's an example:
new p5();
var boop = random(100);
function setup() {
createCanvas(100, 100);
}
function draw() {
background(255, 0, boop);
}

What is the correct way of calling an internal function using the module pattern in Javascript

I am new to Javascript and am still getting my head round the various ways of creating objects i.e constructor+new, prototypal, functional & parts.
I have created what I think is an object factory using the module pattern and want to know what the correct method of calling an internal method would be. Is it via this or function name.
Here is my module:
function chart() {
function my() {
// generate chart here, using `width` and `height`
}
my.sayHi = function(){
console.log('hi');
my.sayBye();
};
my.sayBye = function(){
console.log('Bye');
};
return my;
}
var test = chart();
test.sayHi();
You can see that the first function calls the second using my.sayBye() or is it better to use this.sayBye(). Both produce the same result and run without error.
The module pattern allows you to dispense with the 'this' variable if you want to. I would probably rewrite the above code to look like this and then the question becomes moot.
function chart() {
var hiCount = 0;
function sayHi(){
console.log('hi');
hiCount++;
sayBye();
};
function sayBye(){
console.log('Bye');
};
return {
sayHi : sayHi,
sayBye: sayBye
};
}
var test = chart();
test.sayHi();
In the above code all is defined within the function chart. As JavaScript's scope is at the function level every time the chart function is called a new set of functions will be defined. And a new set of variables can also be defined that are private to the function as they are defined in the function and are not accessible from outside. I added hiCount as an example of how you could do this. The Module pattern allows privacy in JavaScript. It eats more memory than the prototype pattern though as each time a function is declared it is not shared between other instances of the same class. That is the price you have to pay in Javascript to have class variables that are private. I willingly pay it. Removing 'this' from my code makes it easier to understand and less likely that I will fall into problems of misplaced scope.
Using "this" is better approach because you would be able to bind the function directly to the parent function object.And you dont need to return anything from the function.
where as in your case you are explicitly returning another function
Here is the use of "this" approach
function chart() {
this.sayHi = function(){
console.log('hi');
}
}
var test = new chart();
test.sayHi();
Using this approach you would be able to call anything in the prototype of function "chart"
Eg
chart.prototype.hello = function(){
console.log('hello')
}
So you would be able to call the hello function from the same object(test)

what's the real time use of function inside a function in javascript?

Being new to JavaScript, I came across a feature in JavaScript where we can write function inside a function which looks cool, but I didn't understand any practical use of it and also how to call the child function?
var parent = "global";
function Parent() {
alert(parent);
function child() {
alert("i am child");
}
}
So, in the above example function parent embeds child function, but I'm not sure on the following 2 questions:
What's the practical use of such syntax / functionality?
How to call child function?
I'm not sure anyone actually gave you the simple answer for what you asked. Defining the child() function inside the Parent() function is just defining a "local" function whose scope is limited to only within the Parent() function's code. It's analogous to a local variable that only exists inside a function.
So, when you have this:
function Parent() {
function child() {
alert("i am child");
}
}
You've created a new function named child which can be called from the code inside of the Parent() function like this:
function Parent() {
function child() {
alert("i am child");
}
child();
}
This function is truly local to within the Parent() function and cannot be called from anywhere else. So, this will not work:
function Parent() {
function child() {
alert("i am child");
}
}
child(); // this function will be undefined
The simplest reason for defining a function this way is just to contain where it can be used and to reduce potential name conflicts. If you couldn't define local functions like this, then all functions would have to be global (or methods on some object) and you'd potentially have a giant set of possible name collisions. This way, you can define functions within a scope that they apply to and they don't potentially collide with any other functions defined similarly within their own scope.
When you get into more advanced uses of javascript, the child() function also has access to all of the variables of its parent. So, you can do this:
function Parent() {
var msg = "Hello!";
function child() {
alert(msg);
}
child(); // will put up an alert that says "Hello!"
}
This allows those local functions to share all the variables from the parent context without having to pass them all to the function. This can be particularly useful when using callbacks because it allows the callbacks to have access to a whole context even though the callback was called by some other code. Here's a simple example of a callback having access to some useful state.
function blink(elem, numTimes, duration) {
var timer, visible = true;
// callback function that is called
function handleInterval() {
// toggle visible state
var val = visible ? "hidden" : "visible";
elem.style.visibility = val;
visible = !visible;
--numTimes;
if (numTimes <= 0) {
clearInterval(timer);
}
}
timer = setInterval(handleInterval, duration);
}
Here you notice that the handleInterval() function has access to not only the local variables from the blink() function, but also the arguments passed to it. This allows us to keep some state going for the setInterval() without using global variables. There's also a more advanced thing going on here called a closure. Closure's can be a bit complicated of a concept, but understanding a couple uses is generally fairly simple.
In this case, the blink() function gets called. It's job is to create an interval timer that, when called will toggle the visibility state of the passed in element. After a certain number of blinks, it will stop the interval timer. But, all the blink function does is call the setInterval() function to schedule the interval timer. It then immediately finishes and is done executing. But, because the setInterval() function has been schedule and it has been passed a reference to the handleInterval() function and that function is in the scope of the blink() function, then all the local variables of the blink() function are "kept alive" and operating even though the blink() function has already finished executing. In fact, these variables will be uniquely kept alive until the timer is stopped and nothing can call handleInterval() any more. If javascript didn't have this capability, then a number of variables in this simple solution would have to be declared as global variables or properties of some object that persists for the duration of this activity. This technique allows the code to much cleaner and self-contained.
Local functions don't have to be named. They can also be anonymous. A more typical way to implement blink() would be like this using an inline anonymous function callback instead of giving it a name:
function blink(elem, numTimes, duration) {
var timer, visible = true;
timer = setInterval(function() {
// toggle visible state
var val = visible ? "hidden" : "visible";
elem.style.visibility = val;
visible = !visible;
--numTimes;
if (numTimes <= 0) {
clearInterval(timer);
}
}, duration);
}
If you're only ever calling this function in one place, then it doesn't really need to be declared separately and given a name. It can, instead be defined inline like this as an anonymous function.
This concept is mainly used in OOJS (Object Oriented JavaScript). Consider the example below:
var Employee=function(ename,eage){
var _name=ename;
var _age=eage;
this.getName=function(){return _name;};
this.getAge=function(){return _age;};
};
var e1=new Employee("Xyz",45);
var e2=new Employee("Abc",23);
e1.getName(); //output=Xyz
e1.getAge(); // output=45
and so on ...
It's a closure which is a way to control scope in JavaScript. Anything defined inside the closure is not visible outside the closure. With a small modification to your function you can call it like so:
var parent = "global";
function Parent(a) {
alert(parent);
function child(b) {
alert(a + b); //child can see both a and b
}
return child;
}
parent(1)(2);
This can be used to implement currying which is explained here Javascript curry - what are the practical applications?

How do I make a nonexistent (non-member, non-global) method invocable without using eval?

Let's start from the code:
function say(name) {
var ghost=function () {
function ghost() {
alert('!');
};
return body;
};
eval("var body=''+"+name+';');
eval(name+('=('+ghost).replace('body', body)+')();');
eval(name+'();');
}
function Baal() {
if ('undefined'===typeof ghost) {
say('Baal');
return;
}
ghost();
}
say('Baal'); // or just Baal();
Looks like that saying the devil's name invoke his presence (well, maybe he needs somebody for spiritual possession) ..
As you can see the ghost doesn't exist along with Baal, but we can invoke it since there're evals in say(name).
say(name) reassigns Baal to its code body as a closure and makes it captured a ghost method, that's how things work. But I'm trying to avoid eval ..
So .. let me reword the question:
How do I make a nonexistent(and not a member or global) method invocable without using eval?
Let me rephrase your question, just to make sure I’ve got it. Given a function, you want to put a new variable in its scope, without that scope being the global scope or a scope shared between the caller and the subject, without using eval (or the equivalent new Function and other hacks depending on the environment).
You can’t.
In the case you just mentioned, you could define one function, base(), that uses arguments.callee.caller.
Don’t do that.
The short answer: You don't.
That scope is not available. If you were to attach the scope then it would be available inside of the scope used. You could then access the method handles. I assume this is not what you were looking for, but here is what that would look like. demo
function say(name){
var methods = {};
methods.Baal = function(){
alert("!");
};
return methods[name];//this could invoke as well: methods[name]()
}
var handle = say('Baal');
handle();
What your evals break down to is something along these lines (although with dynamic content from string building - this is the end result)
function say(name) {
var Baal = (function () {
function ghost() {
alert('!');
};
return function(){
if ('undefined'===typeof ghost) {
say('Baal');
return;
}
ghost();
}
})();
Baal();
}
say('Baal'); // or just Baal();
Note that the meat of what happens here is from the function Baal, namely that it calls a hardcoded ghost() which in turn calls a hardcoded alert. Why go through all of this trouble to access a hardcoded function?
A better way would be to inject this function as a callback which expects some parameters to be injected.
jsFiddle Demo
function say(callback){
var params = "!";
if( typeof callback == "function" ){
callback(params);
}
}
say(function(params){
alert(params);
});
It's very difficult for me to read through your code and figure out what you are trying to accomplish with it, but it appears that you are trying to introduce a variable into the current scope so that you can call it. You cannot do this in javascript with the method that you demonstrated. Scoping only ever "flows down". By that I mean that a variable or function defined within a function will only be available to that function and any other functions defined therein. Your function named ghost will only ever be available within the function where it is defined, regardless of when that function is evaluated.
What you can do, however, is write a function that returns a function. You can then call that function and assign the result to a variable in the scope where you want to expose functionality. Doing that would look something like this.
function defineSpecialAlert() {
return function(name) {
alert(name + "!");
};
}
var newlyDefinedMethod = defineSpecialAlert();
newlyDefinedMethod("Baal");
So if I understand, it seems like you want to create an alias of eval: Something like
#Note this code is not intended as a solution, but demonstrates
#an attempt that is guaranteed to fail.
#
function myAlias(ctx) {
eval.call(ctx, 'var ghost = 42');
}
myAlias(this);
alert(ghost);
Javascript allows many funky sleight-of-hand tricks especially with closures, but this is maybe the one impossible thing that javascript cannot do. I've tried at length to do this exact same thing, and I can tell you that you'll run into nothing but complaints from the browser, saying that eval cannot be re-contexted or aliased in any way.

Access a javascript variable from a function inside a variable

Hello i have the following issue i am not quite sure how to search for it:
function(){
var sites;
var controller = {
list: function(){
sites = "some value";
}
}
}
So the question is how to access the sites variable from the top defined as
var sites
EDIT:
Here is a more complete part. i am Using marionette.js. i don't want to define the variable attached to the Module (code below) variable but keep it private to the Module, hope that makes sense. Here is the code that works:
Admin.module("Site", function(Module, App, Backbone, Marionette, $, _ ) {
Module.sites = null;
Module.Controller = {
list: function (id) {
Module.sites = App.request("site:entities");
}
};
});
and i would like instead of
Module.sites=null;
to do
var sites;
That sort of thing does make a difference right? Because in the first case i would be defining an accessible variable from outside where as the second case it would be a private one. i am a bit new to javascript so please try to make it simple.
if you are looking for global access, just declare the variable outside the function first, make your changes to the variable inside the function, then you can get the value whenever you need it.
I have found some info on this: sadly what i am trying to do doesn't seem possible.
Can I access a private variable of a Marionette module in a second definition of that module?
So i guess i have to do _variable to make developers know its private.
Disclaimer: I have no experience using Marionette, however, what you're describing sounds very doable.
One of the most powerful (in my opinion) features of JavaScript is closures. What this means is that any function declared from within another function has access to the variables declared in the outer function.
For example:
var func;
function foo() {
var answer = 42;
func = function () {
// I have access to variable answer from in here.
return answer++;
};
}
// By calling foo(), I will assign the function func that has access "answer"
foo();
// Now I can call the func() function and it has access to the "answer"
// variable even though it was in a scope that doesn't exist anymore.
// Outputs:
// 42
// 43
console.log(func());
console.log(func());
What this means is that if you declare var sites from within your module definition function as you described, you should have access to it from within any of your inner anonymous functions. The only exception is if Marionette is re-writing your functions (by using the Function function and toString()), which seems unlikely but possible.
Your original example should would as described, my suspicion is that there is something else going wrong with the code that is unrelated to your scope.

Categories

Resources