Seems like I can only create a global variable for this to work but here is what would be ideal. I would like to pass a variable to an object which has keys that reference functions. In the function I am referencing I would like to set either that variable or one that was defined within the function that called it and pass it back:
jsfiddle
var methodHandler = {
'a-key': function () {
aVariable = document.getElementById('a-container');
}
}
function sample() {
var aVariable;
methodHandler['a-key']();
console.log(aVariable);
}
sample();
Because of scoping, you can't really do it that way. However, you could restructure it like this and get a similar result:
var methodHandler = {
'a-key': function () {
return document.getElementById('a-container');
}
}
function sample() {
var aVariable = methodHandler['a-key']();
console.log(aVariable);
}
sample();
You should use the this element. The this element, when referenced inside a function of the object, represents the object itself, so doing this.foo = 1 will actually create a property called foo with the value of 1 in your object.
Here is the correct form of the code:
var methodHandler = {
'a-key': function () {
this.aVariable = document.getElementById('a-container');
return this.aVariable;
}
}
function sample() {
// You can do this:
methodHandler['a-key']();
console.log(methodHandler['aVariable']);
// Or you can do this instead:
console.log(methodHandler['a-key']());
}
sample();
When you call methodHandler['a-key'](), the property aVariable will be set in your object, so if you log the object you'll see this:
console.log(methodHandler);
// Object {a-key: function, aVariable: div#a-container}
Related
I can store a function in a variable and call it later like this
var storedFunction = functionName;
//Later On
storedFunction(); //Equivalent to functionName()
How can I store a function like this and call it later, also executing this when its called so this would be the
var storedFunction = this.function1().function2();
Later I could call it like this and this would be the class.
class MyClass {
method() {
storedFunction();
}
}
If you have a function like this :
function myFunction(){
return {
function inner(){
return 'some data'
}
}
}
When you call myFunction with myFunction() returned value is an object like this:
{
inner: function (){ return 'some data'; }
}
If you want to store inner function just need store your value with it's key from returned object, like this:
let myInnerFunction = myFunction().inner;
...
//and when you want call that
myInnerFunction ()
In your case this is correct:
let storedFunction = this.function1().function2;
If you want to run function1 and function2 when you call there is a simple way:
let storedFunction = () => {
return this.function1().function2();
}
// or without arrow function
let storedFunction = function () {
return this.function1().function2();
}.bind(this)
The dot operator (.) is the object access operator. That means whenever you see it (not related to a number), the code is attempting to access a property or method (function) of that object.
That means: this.something is attempting to access the something property on an object referred to as this.
Related, then function1().function2() means function2() must be a method of an object too. But, in this case, the object must be returned from function1() in order for this to work.
So here is some sample code that would do what you expect.
function function1() {
return {
function2: () => {
console.log('called function2 from function1 on "this"');
}
}
}
function1.bind(this);
this.function1().function2();
// Using class syntax
class OtherClass {
function2() {
console.log('Used class keyword');
}
}
class MyClass {
constructor() {
this.veryOddThingToDo = this.function1().function2;
}
function1() {
return new OtherClass();
}
}
const myClass = new MyClass();
// Get reference to function2() from "MyClass.function1()" call
const oddness = myClass.veryOddThingToDo;
// This is exactly: this.function1().function2() referenced"
oddness();
is there any way to get function reference when i'm inside function?
var arrayOfFunction = [ myFunction ];
arrayOfFunction[0]();
function myFunction() {
removeFromArray( thisFunctionReference ) // how to get function self reference here?
};
function removeFromArray(functionRef) {
index = arrayOfFunction.indexOf(functionRef);
if (index > -1) {
arrayOfFunction.splice(index, 1);
}
}
In JavaScript, functions are first class members and thus behave like any other object. You can just refer to it by name like this:
myFunction.property = 5;
function myFunction() {
console.log(myFunction.property) //logs 5
console.log(myFunction) // logs the function
};
myFunction();
You can do following as well
removeFromArray(arguments.callee);
Whether you should do that or not will depend on whether you are planning to use "strict" mode in your app. More info in documentation.
In first alert(this.child) returns an object, second it returns undefined whereas I would expect same result. Why and how to fix it ?
https://jsfiddle.net/7jnyozx1/2/
var Child = (function() {
function Child(data) {
}
return Child;
})();
var ChildModel = (function() {
function ChildModel(data) {
this.data = data;
this.child = new Child(data);
alert(this.child); // TEST OK : object
}
function local() {
alert(this.child); // TEST KO : undefined
}
ChildModel.prototype.call = function() {
local();
}
return ChildModel;
})();
data = "hello";
var childModel = new ChildModel(data);
childModel.call();
Because the function local is in no way related to the object. You could put that function at the top of your file and it would work in the exact same way.
You could do local.apply(this); to pass the this from the call method to the function, but you might as well make local a prototype function as well.
this inside of local is scoped to the global object (window). In order to make the local function scoped to your expected this binding (coming from ChildModel) you would need to pass the this binding in from the prototype call.
ChildModel.prototype.call = function() {
local.call(this);
}
function myClass() {
this.nums = [1,2,3];
this.divisor = 2;
}
myClass.prototype.divideNumsByDivisor = function(){
return this.nums.map(function(num) {
return num*this.divisor;
});
}
myClass.divideNumsByDivisor() was suposed to multiply each number on it's member variable nums to the value on it's member variable divisor.
This is not working because the function function(num) { return num*this.divisor; } is pointing this to a wrong object.
According to MDN, the 2nd argument to .map(fn, thisArg) is what you want the this ptr to be set to when the callback function is called and it will be set to the global object (e.g window) if you don't pass the 2nd argument.
So, you can make your example work like this:
function myClass() { this.nums = [1,2,3]; this.divisor = 2; }
myClass.prototype.divideNumsByDivisor = function(){
return this.nums.map(function(num) { return num*this.divisor; }, this);
}
You need to define a reference to your instance in the scope then get it later inside a different instance. Update your method to this
myClass.prototype.divideNumsByDivisor = function(){
var me = this;
return this.nums.map(function(num) { return num*me.divisor; });
}
I know how to access the below member function when it's written like this:
var blady_blah=
{
some_member_function: function ()
{
}
}
I access it from outside doing blady_blah.some_member_function()
But how do I access the member function when it's written like this:
(function() {
some_member_function: function ()
{
}
})();
Braces, { }, are used to define both object literals and function bodies. The difference is:
var name = {}; // Object literal
Which you may also see written as
var name = {
};
That's just the same but with some space in between so it's still an object literal, and unfortunately it looks very similar to:
var name = function () { // Function body
};
An object can have members:
var name = {
member: "string"
};
Whereas a function cannot; a function has statements:
var name = function () {
do_something();
var result = do_something_else();
};
You can't write
var name = function () {
member: "string"
};
Because you've mixed the two uses of { } together.
A variable can be defined within a function, but it can't be seen outside the function - it's within the function scope:
var name = function () {
var something_useful = string;
};
The second example is a closure (it just happens to have a syntax error inside). Minus the bad syntax, your self-evaluating anonymous function looks like this:
(function() {
})();
If you'd like, you can define functions inside this that will be invisible to the outside world. This is useful if you're interested in maintaining a clean global namespace, for example with library code.
(function() {
function utilityFunctionFoo() {
}
function utilityFunctionBar() {
}
})();
Of course, if you'd like to call any of these functions from the outside world, you're out of luck. Or are you? Actually, there's another way to define a function:
var foo = function() {
}
That's exactly the same as writing:
function foo() {
}
...Except that when written in the second style, you can actually omit the var keyword and create a global variable! Bringing it all together:
(function() {
publicData = "stuff accessible from outside anonymous function";
var privateData = "stuff that stays inside anonymous function";
function utilityFunctionFoo() {
}
function utilityFunctionBar() {
}
usefulFunctionExport = function() {
utilityFunctionFoo();
utilityFunctionBar();
}
})();
usefulFunctionExport();
You can't access it after the function it's in terminates. It's a local variable that goes out of scope when its parent function ends.
You should make the main function be a constructor so that it returns a new instance of a class (you could name it Blahdy_blah) with the member function as one of its properties.
Look up constructors, their return values, and accessing member variables.
If you want to execute the function you need to return an object that exposes the function.
var LIB = (function() {
var fn = {
member_function : function(){}
};
return fn;
})();
and to call
LIB.member_function();
(function() {
blady_blah.some_member_function();
})();
If you need to add stuff into it you would write it like this.
(function() {
blady_blah.some_member_function(function(){
// Do stuff...
});
})();