Make a local function as global - javascript

In Javascript with ProcessingJS.
If I define a function outside the draw function, how can I pass this function to the draw function (without copying and pasting inside the draw function)?
var myFunction = function()
{
code;
}
var draw = function(){
myFunction();
};
How do you make a function global?
I use a limited environment, Khan Academy, and only the simplest functions and commands are available.
Thanks for your replies, and sorry to be a beginner.

You could pass your function as a parameter. For example:
var myFunction = function() {code;}
var draw = function(f) { f(); };
draw(myFunction);

I use Khan Academy too. There are strict syntax rules that don't make sense anywhere else. To answer the question,
var myFunction = function () {
/* Stuff */
}, draw = function () {
myFunction();
};
will work just fine.

What you are asking for is to call myFunction inside the draw function.
Here is how you would do that:
var myFunction = function(){
//your code here
}
var draw = function(fun){
fun();
}
Basically, if you want to call myFunction() inside the draw() function, you have to pass a function into draw(), this is called a parameter. Like so: var draw = (fun) Here, fun is a function being passed into draw. Now you just need to call it using fun();
Good luck!

You're using invalid syntax. If you want to make a global function and call it inside draw(), just declare it like a regular function:
var myFunction = function () { // <-- note the "=" sign and "function" keyword here
code;
};
var draw = function (){
myFunction();
};

Related

Passing Object Parameter To Another Function - Javascript

The current code fails because element.style.backgroundColor = "yellow" is not referencing the object that I passed in as a parameter (mydiv).
How do I give func2 the reference to the element "mydiv"? I know this code does not require func2, as what can be done in func2 can be done in func1, but for my actual code I need to pass the object to another function.
How can I do this in JavaScript without jquery?
Thanks.
function func1() {
var a = document.getElementById("mydiv");
a.style.backgroundColor = "black";
function func2(a);
}
function func2(element) {
element.style.backgroundColor="yellow";
}
There is no need to use function in order to call func2, function keyword only use when you need to define new function.
function func1() {
var a = document.getElementById("mydiv");
a.style.backgroundColor = "black";
func2(a);
}
function func2(element) {
element.style.backgroundColor="yellow";
}
Just remove the word function from function func2(a);.
Your code should look like this.
function func1() {
var a = document.getElementById("mydiv");
a.style.backgroundColor = "black";
func2(a); //You just need to update this line.
}
function func2(element) {
element.style.backgroundColor="yellow";
}
Try to google for JavaScript Hoisting to get more details.

Accessing sibling functions within a self-executing function

I feel like I'm making a really simple error here. Essentially, I'm just trying to access a function from another function within a self-executing function. Is there any reason why printConfirmation isn't being called? It seems that eventHandlers isn't properly working either.
(function(){
var targetZone = document.getElementById('target-zone');
var eventHandlers = function(){
targetZone.addEventListener('click', printConfirmation);
};
var printConfirmation = function(){
targetZone = targetZone.classList;
targetZone.add('clicked');
};
})();
It is a hoisting issue, change to function declarations instead of function expressions and it will work:
(function(){
var targetZone = document.getElementById('target-zone');
function eventHandlers(){
targetZone.addEventListener('click', printConfirmation);
}
function printConfirmation(){
targetZone = targetZone.classList;
targetZone.add('clicked');
}
eventHandlers();
})();
Edit: Also, as Daniel pointed out, you need to actually call eventHandlers()

Assigning a function to a variable in JavaScript

function abc(){
//multiple variables and functions
a:function(){alert("a")};
}
function test(){
var k=abc();
k.a();
}
In the above case, I have a huge function abc() to be assigned to a variable. I want to call the member functions that are visible, like a() from the variable. Is this possible to implement and please give me a sample code if so.
When you include the parenthesis after your function, you're assigning the result of the function to your variable.
If you want to assign the function itself, just omit the parenthesis:
var k = abc;
k.a();
EDIT
Per #Kuba Wyrostek's answer, and #Pointy's comment, that a() function won't be properly exposed.
You'll need to take a look at the Module Pattern. What you need to do is to assign a function to a variable, and have that function return the functions that you want to be able to use outside of that function. This helps with encapsulation.
It's a little hard to tell from your code in the comment exactly what is the user-generated code, but I'll do my best.
var abc = (function () {
var grabApi,
initialize;
// Just an example of how to assign an existing function
// to a property that will be exposed.
grabApi = SCORM2004_GrabAPI();
// This is an example of how to have a property that will be
// exposed be a custom function passing a parameter.
initialize = function(initString) {
return SCORM2004_GrabAPI().Initialize(initString);
};
return {
getApi: grabApi,
init: initialize
}
}());
You can then use this abc object like this throughout your code. Again, this is trying to give an example of how to do what I think you're trying to do based on your comment.
// Assign the SCORM2004_GrabAPI function to a variable.
var SCORM2004_objAPI = abc.getApi();
// Call the Initialize function with an empty string.
abc.init("");
Hmmm… contrary to #krillgar's answer, I believe you were expecting your abc() to return new object. Something like this:
function abc(){
var privateVar;
return {
//multiple variables and functions
a:function(){alert("a")}
}
}
function test(){
var k=abc();
k.a();
}
You should make it an object. In this way you can access its property a.
var abc ={
a:function(){alert("a")}
}
function test(){
var k=abc;//Ofcrse remove the parenthesis
k.a();
}
test();

javascript use named function as method in an object

I have an object, lets call it myObject, and a named function myFunction.
Can I create a method in myObject, lets call it myMethod, so that whenever I call myObject.myMethod I'll actually call myFunction.
I know i can create a new function for myMethod, and probably could make it be a wrappeI for myFunction, but is there a better way? or am I doing this all wrong
If I understand your question correctly, this is all you need to :
var myObject = {};
var myFunction = function() {/* code goes here*/};
myObject.myMethod = myFunction;
Because of how JavaScript works, though, this wouldn't become an object-specific function this way, so you couldn't track state with it. It would be similar to a static function in Java.
i think you are confusing your words. methods of an object are generally functions. like so-:
var myObject = {
x:0,
y:0,
getX: function () {
return this.x;
},
getY: function () {
return this.y;
}
};
you can add any number of methods/functions.

Unable to access the object using `this`. `this` points to `window` object

I have this Javascript constructor-
function TestEngine() {
this.id='Foo';
}
TestEngine.prototype.fooBar = function() {
this.id='bar';
return true;
}
TestEngine.prototype.start = function() {
this.fooBar();
}
TestEngine.prototype.startMethod = function() {
inter = setInterval(this.start, 200);
}
var test = new TestEngine();
test.startMethod();
Gives me this error -
Uncaught TypeError: Object [object global] has no method 'fooBar'
I tried console.log and found out that when I call this.start from within setInterval, this points to the window object. Why is this so?
The this pointer can point to one of many things depending upon the context:
In constructor functions (function calls preceded by new) this points to the newly created instance of the constructor.
When a function is called as a method of an object (e.g. obj.funct()) then the this pointer inside the function points to the object.
You can explicitly set what this points to by using call, apply or bind.
If none of the above then the this pointer points to the global object by default. In browsers this is the window object.
In your case you're calling this.start inside setInterval. Now consider this dummy implementation of setInterval:
function setInterval(funct, delay) {
// native code
}
It's important to understand that start is not being called as this.start. It's being called as funct. It's like doing something like this:
var funct = this.start;
funct();
Now both these functions would normally execute the same, but there's one tiny problem - the this pointer points to the global object in the second case while it points to the current this in the first.
An important distinction to make is that we're talking about the this pointer inside start. Consider:
this.start(); // this inside start points to this
var funct = this.start;
funct(); // this inside funct (start) point to window
This is not a bug. This is the way JavaScript works. When you call a function as a method of an object (see my second point above) the this pointer inside the function points to that object.
In the second case since funct is not being called as a method of an object the fourth rule is applied by default. Hence this points to window.
You can solve this problem by binding start to the current this pointer and then passing it to setInterval as follows:
setInterval(this.start.bind(this), 200);
That's it. Hope this explanation helped you understand a little bit more about the awesomeness of JavaScript.
Here is a neat way to do OOP with javascript:
//Global Namespace:
var MyNamespace = MyNamespace || {};
//Classes:
MyNamespace.MyObject = function () {
this.PublicVar = 'public'; //Public variable
var _privatVar = 'private'; //Private variable
//Public methods:
this.PublicMethod = function () {
}
//Private methods:
function PrivateMethod() {
}
}
//USAGE EXAMPLE:
var myObj = new MyNamespace.MyObject();
myObj.PublicMethod();
This way you encapsulate your methods and variables into a namespace/class to make it much easier use and maintain.
Therefore you could write your code like this:
var MyNamespace = MyNamespace || {};
//Class: TestEngine
MyNamespace.TestEngine = function () {
this.ID = null;
var _inter = null;
//Public methods:
this.StartMethod = function (id) {
this.ID = id;
_inter = setInterval(Start, 1000);
}
//Private methods:
function Start() {
FooBar();
console.log(this.ID);
}
function FooBar() {
this.ID = 'bar';
return true;
}
}
//USAGE EXAMPLE:
var testEngine = new MyNamespace.TestEngine();
testEngine.StartMethod('Foo');
console.log(testEngine.ID);
Initially, the ID is set to 'Foo'
After 1 second the ID is set to 'bar'
Notice all variables and methods are encapsulated inside the TestEngine class.
Try this:
function TestEngine() {
this.id='Foo';
}
TestEngine.prototype.fooBar = function() {
this.id='bar';
return true;
}
TestEngine.prototype.start = function() {
this.fooBar();
}
TestEngine.prototype.startMethod = function() {
var self = this;
var inter = setInterval(function() {
self.start();
}, 200);
}
var test = new TestEngine();
test.startMethod();
setInterval calls start function with window context. It means when start gets executed, this inside start function points to window object. And window object don't have any method called fooBar & you get the error.
Anonymous function approach:
It is a good practice to pass anonymous function to setInterval and call your function from it. This will be useful if your function makes use of this.
What I did is, created a temp variable self & assigned this to it when it is pointing your TestEngine instance & calling self.start() function with it.
Now inside start function, this will be pointing to your testInstance & everything will work as expected.
Bind approach:
Bind will make your life easier & also increase readability of your code.
TestEngine.prototype.startMethod = function() {
setInterval(this.start.bind(this), 200);
}

Categories

Resources