0
var f2 = undefined
var f1 = function () {
    f2 = this
    console.log('here')
}
f1()
f2()

Outputs

f2()
^
TypeError: undefined is not a function

How to set f2 to f1 from teh inside of f1() ?

exebook
  • 32,014
  • 33
  • 141
  • 226

2 Answers2

2

This isn't actually the right way to set it, but even if it was, you never called f1, so the value of f2 could never change. You would need this:

var f2 = undefined;
var f1 = function () {
    f2 = this;
    console.log('here');
}
f1();
f2();

That said, the above still won't work, because this inside of a standalone function is not the function. In a browser, it will be the window object, and you'll get something like TypeError: object is not a function. In other contexts (e.g., node.js) it will depend on how they implement the top-level object, if any.

There is a great question explaining how functions work with the this keyword. In this case you will not be able to do it without referring to the outer function by name or changing how you call f1:

// Referring to f1 by name..
var f2 = undefined;
var f1 = function () {
    f2 = f1;
    console.log('here');
}
f1();
f2();

// .. or using the apply method to change the value of "this", though still
// referring to f1 by name in some sense (at the call site)
var f2 = undefined;
var f1 = function () {
    f2 = this;
    console.log('here');
}
f1.apply(f1);
f2();

Side note, semicolon elision is gross.

Community
  • 1
  • 1
Chris Hayes
  • 11,471
  • 4
  • 32
  • 47
1

I'm not sure of any way to do it without a wrapper.

var wrapper = {}

wrapper.f1 = function () {
    wrapper.f2 = wrapper.f1
    console.log('invoked', this)
}

wrapper.f1()
wrapper.f2()

I'm not sure if that works in your actual use case or not.

var whatIsThis = function() {
    console.log('invoked', this)
}

whatIsThis()

On a related note, this second example shows the window object in a browser. I'm not sure what it will show in node.

timetocode
  • 71
  • 3