Shorthand to call function from scope - javascript

If I have a function as follows (pseudocode) :
function doSomething (input) {
input.something(something);
do(input, function (res) {
input.send(res)
}
}
However, I want to be able to run it from another area, and the only shared variable between the two is $scope, so I do something like this:
$scope.doSomething = function (input) {
doSomething(input);
}
Now, I can call doSomething using $scope. However, creating an extra function to do it is quite messy. Ideally, I'd like to be able to do something like this:
$scope.doSomething = doSomething(input);
That doesn't work though. Is there a similar shorthand you can use to create a reference to a function from another, without the need for a 'useless' function?

You should be able to do that if you've already declared the function. But instead of using doSomething(input) which is actually calling the function, use it without the brackets like so
$scope.doSomething = doSomething;

what you need to do is assign function pointer.
$scope.doSomething = doSomething;
what you are currently doing $scope.doSomething = doSomething(input); is assigning function call result, rather than pointer

Related

How to access function inside of function?

today my question is asking how I would access a function inside a function. So, for example, I have a button, and if I click it, it would alert. The thing is, if you have a function surrounding the function, the inside function with the alert would not alert.
Here's an example:
html:
<button onclick="doStuff()">Alert</button>
js:
function nothing() {
var doStuff = function() {
alert("This worked!")
}
}
so the doStuff() function would not work. Can someone help me find a way to access it?
#Joseph the Dreamer is ultimately correct, but if you were dead set on calling a function that's nested in another function you could use an OOP approach.
Create a javascript "class" object and scope your function to "this":
function Nothing() {
this.doStuff = function() {
alert("works");
}
}
Next you add an id to your button,
along with a click event listener
Then, inside your click event you can call doStuff within the Nothing "Class" function like this:
var object = new Nothing();
object.doStuff();
https://jsfiddle.net/me7fek5f/
You can't. That's because it's enclosed in a scope that you can't really access globally. The only way you can access it is to expose it somewhere outside nothing.
Is this a homework question?
You're probably asked to do something like this:
function nothing() {
var doStuff = function() {
alert("This worked!")
}
var yourButton = getYourButton();
attachClickListener(yourButton, doStuff);
The implementations of getYourButton and attachClickListener are left to the reader.

Self invoking function written with 'var name = " in the front - bad practice?

In my knockout.js project I wrote some self invoking functions like this:
var addMarkers = function () {
ko.utils.arrayForEach(self.sectionList(), function (sectionItem) {
ko.utils.arrayForEach(sectionItem.placeList(), function (placeItem) {
placeItem.marker.addListener('click', function () {
map.panTo(placeItem.marker.getPosition());
});
});
});
}();
The function works without problems, however in JSLint the "var addMarkers" was highlighted as unused variable. That makes me wonder if I should the function like this, or just make anonymous because it is a better practice?:
function addMarkers (){ code to be executed };
Assigning the result of a self-executing function is often useful. In particular, I like to define my main viewmodel this way, because
I don't need a prototype for my viewmodel
I'm not likely to need more than one instance of a viewmodel
The reason you would use a self-executing function is that you need a local scope for whatever you're doing, to isolate it from surrounding scope. The reason you would assign a variable from it is that you want it to return a value you will use later. In your example, neither of these is true.

Accessing instance functions inside controller from function on $scope

I have a controller that looks like this:
function controller($scope)
{
this.helper() = function()
{
// some processing
};
$scope.doSomething = function()
{
helper();
};
}
When doSomething is called, I get an error saying that helper() is not defined. Putting 'this' in front of the call to helper() doesn't work either as 'this' here refers to $scope and not to the controller instance.
My question is: is there a way to call such local helper functions from within a function on the scope? (I know I could just put helper() on the $scope too but would rather not as it's strictly a convenience function, not something to be called from the view.)
The reason for structuring the code like this is to facilitate separate testing of the helper() function from a unit test.
function controller($scope)
{
this.helper() = function()
{
// some processing
};
var helperScope = this;
$scope.doSomething = function()
{
helperScope.helper();
};
}
Of course, give it a more descriptive name than that, but the basic idea is to assign this to a variable within the scope you want.

call a js function based on the argument passed

I'm trying to call a js function within another one, but use the argument to specify the function. ie depending on the argument passed, it will call a different function
function toggle(n){
if (sessionStorage['toggle'+n]== 0){
check+n();
}
else
}
So, for example, if the argument 'Balloons' was passed as n, then it will call the function checkBalloons(). "check+n();" is not currently working here. Sorry for my lack of simple js syntax!
If the function is defined in the global scope (browser) you can do:
window["check"+n]();
or some tenants like Node.js you would access it from global object.
global["check"+n]();
if it is a part of some other object then you would do the same.
obj["check"+n]();
Functions and properties defined on an object can be accessed using [] convention as well. i.e obj["propFuncName"] will give you reference to it, so in case of methods you add () to invoke it.
If the function is global, you would do this:
window["check" + n]();
or, you could put your function in an object like so:
myNamespace = {};
myNamespace.checkSomething = function(){ /* ... */ }
// call it like this:
myNamespace["check" + n]();
The answers thus far are correct, but lack explanation.
In JavaScript, you cannot call a function by name when that name is a string. What you can do is retrieve a value from an object by name, and if that value happens to be a function, you can then call it. For example:
var myObject = {};
myObject.myFunction = function() { alert('test!'); };
// Get the property on `myObject` called `myFunction`
var theFunctionLookup = myObject['myFunction'];
// Since that property was a function, you can call it!
theFunctionLookup();
In the browser, functions that are defined in the global scope are attached to the window object. For example, this works:
function myFunction() { alert('test'); }
var theFunctionLookup = window['myFunction'];
theFunctionLookup();
You can shorten the last two lines into one:
function myFunction() { alert('test'); }
// Look up and call the function in one line.
window['myFunction']();
For the same reasons, you can use a dynamically-calculated string to look up functions.
function checkBalloon() {
alert('checking balloon');
}
function toggle(n){
if (sessionStorage['toggle'+n]== 0){
window['check' + n]();
check+n();
}
}
toggle('Balloon');
if you do this way:
if (sessionStorage['toggle'+n]== 0){
window["check" + n]();
}
will work

Redefining a function which is part of another function

I have a function that looks like this:
function outer() {
function inner_1() {
alert('inner_1');
}
function inner_2() {
alert('inner_2');
}
function inner_3() {
alert('inner_3');
}
inner_1();
inner_2();
inner_3();
}
I need to call outer(), but I want to replace inner_1() with another function.
I have tried this:
new_outer = outer;
new_outer.inner_1 = function() {
alert('my new inner function');
};
If I try to call the newly redefined inner_1 like this:
new_outer.inner_1();
it works as expected ('my new inner function' is alerted).
But if I try to call the outer function:
new_outer();
the old version of inner_1 is called.
I want to redefine inner_1 and the call outer. How can I achieve this?
This seems like a really bad idea so I am not going to post any code. However, if you are pursuing the answer for "educational purposes only", I will just hint that although you cannot easily redefine a function from outside its scope (as per your example), there is nothing stopping you from redefining a function attached to a function object.
I do think, however, there is a better solution to whatever the problem you are trying to solve is.

Categories

Resources