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()
Related
I have a function in javascript
var fn = function(){
var obj = {result: true};
return obj.result;
};
I have access to the function, but I need to get the inner obj. Is there a way to do that?
EDIT: Thanks to the answers below, I have managed to come up with a solution.
https://stackoverflow.com/users/1447675/nina-scholz 's answer was the closest, so I marked it as the solution.
var f2 = function fn(){
fn.obj = {result: true};
return fn.obj.result;
};
A client of this function can use it like the following :-
var myFunction = f2;
The function must be called though, to access the inner variables
myFunction();
After that one can do the following.
console.log(myfunction.obj);
This seems to be working. I would, however like to know if this is a good practice.
You cannot access the inner object outside of the scope of the function.
you can access obj when you make it public.
function fn() {
fn.obj = { result: true };
return fn.obj.result;
}
console.log(fn());
console.log(fn.obj.result);
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();
};
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();
Why does the marked line fail to find protectedACMember?
var Module = (function (ns) {
function AbstractClass() {
this.protectedACMember = "abstract";
this.abstractPublicACMethod = function (input) {
this.methodToImplement();
}
}
ConcreteClass.prototype = new AbstractClass();
function ConcreteClass(){
var privateCCMember = "private CC";
var privateCCMethod = function(){
alert(this.protectedACMember); // cant find protectedACMember
}
this.methodToImplement = function(){
privateCCMethod();
console.log('Implemented method ');
}
}
ns.ConcreteClass = ConcreteClass;
return ns;
})(Module || {});
//somewhere later
var cc = new Module.ConcreteClass();
cc.abstractPublicACMethod();
are there any good patterns for simulating private, protected and public members? Static/non-static as well?
You should change that part of code like this:
var self = this;
var privateCCMethod = function(){
alert(self.protectedACMember); // this -> self
}
This way you get the reference in the closure.
The reason is, that "this" is a reserved word, and its value is set by the interpreter. Your privateCCMethod is an anonymous function, not the object property, so if you call it simply by privateCCMethod() syntax, this will be null.
If you'd like "this" to be bound to something specific you can always use .call syntax, like this:
privateCCMethod.call(this)
Another way to ensure that this means what you want is to use bind. Bind allows you to ensure a function is called with a specific value of this.
Most newer browsers support it (even IE9!) and there's a workaround for those that don't.
Bind - MDN Documentation
It fails to find protectedACMember because what the this keyword means changes when you enter the function privateCCMethod. A common practice is to store the outer this for use inside the functions:
function ConcreteClass(){
var privateCCMember = "private CC";
// store the outer this
var that = this;
var privateCCMethod = function(){
alert(that.protectedACMember);
}
...
The rest of your questions are fairly loaded and should probably be posted as a separate question.
I understand the concept of variable scope in the following example, but can someone explain the function-wrapping syntax (...)();, e.g. how do you use it in actually day-to-day JavaScript programming? It's not something that I know from PHP/Java/C#.
window.onload = function() {
var i = 4;
console.log(i); //4
(function showIt() {
var i = 'whatever';
console.log(i); //whatever
})();
console.log(i); //4
};
There are several ways in which this form is useful. One is to lexically scope a segment of code so that its inner variables and methods stay separate from the larger body of code that contains it. In this way, it's JavaScript's way of doing block scoping. But the most common way I use this format is as an alternative to this:
var ret = {
depth:0,
initialized:false,
helper:function() { /*help with some stuff*/ },
initialize:function(){ /*do some initialization code*/ },
action:function(){/*do the thing you want*/}
destroy:function() { /*clean up*/ }
}
The thing that absolutely kills me about this format is it is extremely time consuming to find missing braces and commas. For example, the code above won't work because the's no comma at the end of the action declaration and unless I had pointed it out, you'd have had a hard time finding the problem because when the exception is thrown, it's thrown on the entire statement, not the section that's "causing the problem". This is such a predictable problem that I simply don't use this format any more if I can possibly avoid it. I refuse. Instead, the same can be written much more clearly as:
var ret = (function(){
var self = {},
initialized = false;
var helper = function() { /*help with some stuff*/ };
self.depth = 0;
self.initialize = function() {/*do some initialization*/};
self.action = function() {/*do the thing you want*/};
self.destroy = function() { /*clean up*/ };
return self;
}());
There are two big advantages for me. One, missing braces and commas can be found more easily (when the exception is thrown, the line number will be close to the area where it's missing). And two, you can choose to keep some variables and methods private and you retain all the benefits of the first block of code.
And the last plug I'll give for this format is that the code above (which is sort of like a Singleton) can be converted into a constructor by 1) removing the invocation braces on the outside, 2) changing self = {} to self = this, and 3) optionally removing the return self at the end:
var Ret = function(){
var self = this,
initialized = false;
var helper = function() { /*help with some stuff*/ };
self.depth = 0;
self.initialize = function() {/*do some initialization*/};
self.action = function() {/*do the thing you want*/};
self.destroy = function() { /*clean up*/ };
return self; // this is ignored by the compiler if used as a constructor
};
var ret = new Ret();
This is defining a function showIT (using function showIT() {...}) similar to what you're already familiar with. The () at the end directly invokes the function in the same line as it is defined. That's probably the part that is new to you. Just like you'd say showIT() to invoke the function, you can replace the name with the actual definition and it'll work in Javascript.
JavaScript has function literals. All it's doing is making a function literal, and calling the result of the expression. Is the name what's confusing you? All a name would be used for is referring to the function inside its own body, and it's optional. (Note that that's not compatible with IE 8 and earlier.)
Unlike in C where variable names have block scope, JavaScript (like Pico) has only function scope.
So if you want to create a new name scope you can't just use { ... } as you could in C, you have to use (function() { ... })();.