Javascript call function - Dynamic variable name [duplicate] - javascript

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I am trying to call a function using a variable with it's name.
Here's the code:
var selectedFunc = 'func2';
var myModule = {
func1: function() {
//something here
},
func1: function() {
//something here
}
};
myModule.selectedFunc();
I would normally do this:
myModule.func1();
which will work but I'm trying to use the variable to define it's name, which is not working.
How can I fix this issue?

You can use bracket notation:
myModule[selectedFunc]();

You could call it using the following syntax
setTimeout("myModule."+selectedFunc + "()", 0);
Or even using eval to call it
eval("myModule." + selectedFunc).call();

Use eval.
var selectedFunc = 'func2';
var myModule = {
func1: function() {
return "hello";
},
func2: function() {
return "world";
}
};
window.alert(eval("myModule." + selectedFunc + "()"));

Related

Double function name in javascript [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 4 years ago.
Here is the code sample I have a question about:
var javascriptObject = {
functionName1: function functionName2() {
}
}
I understand the concept of an object in the javascript. I understand everything in the code sample except the functionName2 what is its purpose?
And I saw the code in the real life projects:
init: function init() {
init._base.call(this);
}
The code above does not work if I get rid from the second init. What does that second function name mean in javascript?
Object in JS are just name value pairs nothing more
var javascriptObject = {
functionName1: function functionName2() {
}
}
So what your doing is having a object which has a name of functionName1 which has the value of
function functionName2() {}
The name of the function stored in this value is functionName2 but this also could be omitted since it is not necessary to invoke the function.
For example you could run the function without the functionName2
var javascriptObject = {
functionName1: function () {
return 5;
}
};
var bar = javascriptObject.functionName1();
console.log(bar);

No output from the object functions [duplicate]

This question already has answers here:
Referencing "this" inside setInterval/setTimeout within object prototype methods [duplicate]
(2 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 5 years ago.
This question is from an written test for a company. It looks very confusing. I thought it will print whatever this.name is set to. Bu when I typed the code it shows nothing. I have little knowledge about closures and I think it is related to the problem. I want a little explanation here.
function dd(name) {
this.name = name;
this.go = function() {
setInterval(function() {
return this.name;
}, 2000)
}
}
var tt = new dd("corolla");
tt.go()
You can't get the return value from setInterval in this way. Try with a callback as in the following snippet
function dd(name)
{
this.name=name;
console.log( name );
var _this = this;
this.go=function(cb)
{
setInterval(function() {
cb(_this.name);
},1000)
}
}
var tt=new dd("corolla");
tt.go(function(ret) {
console.log( ret );
})
Also, please note that inside setInteval the value of this is not the same as in the otter function. That's why var _this=this;

Angular get/set variable on scope with this from function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I am adapting a controller to the "controller as" syntax.
But while transforming the code, I remarked that I can't access the "scope" variables with this out of a function.
If I understand the concept of this, then this does access the object it is used in.
As example this code:
this.scopeVariable = undefined;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
this.scopeVariable = result.foo;
});
};
So when I try to set the scopeVariable with this, I actually try to access an object from fooFunction, right?
If this is the case, how can I grab an object outside of the function within the function?
Thanks for your answers!
You have this problem because the this keyword changes definition when in a different scope. That means that if you have a simple object e.g.
var a = {
b: function() {
console.log(this); // => will log the value of "a"
setTimeout(function() {
console.log('just some rubbish');
console.log(this); // => will log inner function scope instead of "a"
}, 200)
}
}
a.b(); // to see the results
To prevent this issue from happening you can reassign this to a variable which will stay intact through deeper scopes like this:
this.scopeVariable = undefined;
var self = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
// using self. instead of this. makes the difference here
self.scopeVariable = result.foo;
});
};
Capturing the this being the scope in a variable: var that = this:
var that = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
that.scopeVariable = result.foo;
});
};

How would I 'wrap' an object and replace all of the functions in it? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Is there a way to wrap all JavaScript methods with a function?
(3 answers)
Closed 8 years ago.
Here's what I want to achieve:
var obj = {
something: 1,
someFunction: function () {
return 'hello';
}
};
wrap(obj).someFunction('hello'); // this should be different from obj.someFunction defined above
wrap(obj).something = 2; // this should still work
Basically, I want to 'wrap' an object and replace all the functions in it with something else.
Here's how I've defined the wrap function:
function hello (v) {
return 'Hello ' + v;
}
function wrap (oldObj) {
var newObj = {};
for (var k in oldObj)
Object.defineProperty(newObj, k, {
get: function () {
if (typeof oldObj[k] === 'function')
return hello;
return oldObj[k];
},
set: function (val) {
oldObj[k] = val;
}
});
return newObj;
}
(hello is just an example replacement function)
When I try to use this, everything in obj gets replaced with a function (i.e even obj.something, which was set to 1, is replaced with a function). I can't seem to find any issues with this code. I've tried debugging it and haven't found the issue yet.
What might be the issue? How else can I solve this problem?
Edit 1: I don't want to replace functions in the object itself, I want to create an entirely new object.

Javascript function definition error [duplicate]

This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 9 years ago.
var add = function addnums(a,b)
{
return a+b;
}
alert("sum is " + addnums(10,20));
why can't i use addnums directly in the above Javascript ?
PS : I know other alternatives, the question is why the above specified method doesn't work.
You can.
var add = function addnums(a,b)
{
return a+b;
}
alert("sum is " + (function(a,b) { return a+b; })(10,20) );
Plus you may shorten the syntax:
var addnums = function(a,b) { ... }
or
function addnums(a,b) { ... }
You have an error writing the function write like the following:
var addnums = function(a,b)
{
return a+b;
}
alert("sum is " + addnums(10,20));
:)
var add; is a declaration. Here add is declared and assigned a function you need not name the function after keyword function, variable name will take the function name when you define a function in this way. I think you understand now.

Categories