Rectangle 27 36

What's a scope?

Actually it's the opposite. Defining a function doesn't create a scope. Calling a function creates a scope.

To put it simply, a scope is the lifespan of a variable. You see, every variable is born, lives and dies. The beginning of a scope marks the time the variable is born and the end of the scope marks the time it dies.

In the beginning there's only one scope (called the program scope or the global scope). Variables created in this scope only die when the program ends. They are called global variables.

For example, consider this program (it's not JavaScript):

x = 10       // global variable x

{            // beginning of a scope
    x = 20   // local variable x
    print(x) // 20
}            // end of the scope

print(x)     // 10

Here we created a global variable called x. Then we created a block scope. Inside this block scope we created a local variable x. Since local variables shadow global variables when we print x we get 20. Back in the global scope when we print x we get 10 (the local x is now dead).

Now there are two main types of scopes in programming - block scopes and function scopes.

The scope in the previous example was a block scope. It's just a block of code. Hence the name. Block scopes are immediately executed.

Function scopes on the other hand are templates of block scopes. As the name suggests a function scope belongs to a function. However, more precisely, it belongs to a function call. Function scopes do not exist until a function is called. For instance:

var x = 10

function inc(x) {
    print(x + 1);
}

inc(3);   // 4
print(x); // 10
inc(7);   // 8

As you can see every time you call a function a new scope is created. That's the reason you get the outputs 4, 10 and 8.

JavaScript only has function scopes. It doesn't have block scopes. Hence if you want to create a block scope then you need to create a function and immediately execute it:

var x = 10;     // global variable x

(function () {  // beginning of a scope
    var x = 20; // local variable x
    print(x);   // 20
}());           // end of the scope

print(x);       // 10

Function scopes can again be of two types - lexical and dynamic. You see, in a function there are two types of variables:

Variables declared inside a scope are bound to that scope. Variables not declared inside a scope are free. These free variables belong to some other scope, but which one?

function add(x) {         // template of a new scope, x is bound in this scope
    return function (y) { // template of a new scope, x is free, y is bound
        return x + y;     // x resolves to the parent scope
    };
}

var add10 = add(10);      // create a new scope for x and return a function
print(add10(20));         // create a new scope for y and return x + y

In contrast to lexical scoping, in dynamic scoping free variables must belong to the calling scope (the scope of the calling function). For example (this is also not JS - it doesn't have dynamic scopes):

function add(y) {   // template of a new scope, y is bound, x is free
    return x + y;   // x resolves to the calling scope
}

function add10(y) { // template of a new scope, bind y
    var x = 10;     // bind x
    return add(y);  // add x and y
}

print(add10(20));   // calling add10 creates a new scope (the calling scope)
                    // the x in add resolves to 10 because the x in add10 is 10

The problem with your first program is that JavaScript doesn't have dynamic scoping. It only has lexical scoping. See the mistake?

function f1() {
    var a = 1;
    f2();
}

function f2() {
    return a;
}

f1(); // a is not defined (obviously - f2 can't access the `a` inside f1)

Your second program is a very big mess:

Here are the mistakes:

  • You never called f. Hence the variable b is never created.
  • Even if you called f the variable b would be local to f.
function f() {
    var b = "barb";

    return function() {
        return b;
    }
}

var x = f();

console.log(x());

When you call x it returns b. However that doesn't make b global. To make b global you need to do this:

var x = f();
var b = x();
console.log(b);

Hope this helped you understand about scopes and functions.

I've been struggling with understanding the differentiation despite reading Eloquent Javascript. Thank you so much for the thorough explanation.

@Aadit M Shah: Your answer is contradictory, at best confusing. First you stated "Defining a function doesn't create a scope. Calling a function creates a scope". Fine. Then in your examples, where the function is defined, then later called, you put the same comment "create scope" for both of them. That conflicts with the statement you made "Defining a function doesn't create a scope". Then you throw in the term "calling scope" without introducing it. Is it scope of the calling function? You probably understand the topic, but I'd clean up a little bit.

@Khnle-Kevin When you create a function no scope is created .When you call a function then a lexical scope is created. When you create a function the function is kept inside the execution context. Execution context is in memory space created when running the program. If you still find it confusing watch the first lesson on Scopes and Closures at Udacity udacity.com/course/object-oriented-javascript--ud015

But Anand, this is what you wrote and I quote word for word, so please don't edit your answer. On the 1st sentence, "When you create a function no scope is created". On the 3rd, "When you create a function the function is kept inside the execution context". Therefore according to you "When you create a function, no scope is created and the function is kept inside the execution context". I do find what you write very confusing.

@Khnle-Kevin Anand did not write this answer. I did. My name is Aadit M Shah. There is only one Aadit M Shah in the world. Also, I edited my answer after your first comment (six months ago). See the revision history of my answer. Now it doesn't contradict itself. Cheers. =)

Lexical scope/closures in javaScript - Stack Overflow

javascript closures lexical-closures
Rectangle 27 203

You need to use $scope.$apply() if you want to make any changes to a scope value from outside the control of angularjs like a jquery/javascript event handler.

function change() {
    alert("a");
    var scope = angular.element($("#outer")).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    })
}

Thanks for the answer. I've tried the Fiddle you've attached but I still get the same "You are great" string even after I click on "click me". I get the alert, just not the string change. Are you seeing changes?

angular.element("#scope")
angular.element($("#scope"))

I know it been a while, but I hope some can answer me on this ... Why does var scope = angular.element($("#outer")).scope(); have to be declared inside the change function? If I move it to the global space it's a no go?

@MarcM. I think it has to do with Angular's scope recreation. By the time you're using the change function, the previous scope the global var was pointing to may no longer exist (due to the recreation).

AngularJS access scope from outside js function - Stack Overflow

angularjs angularjs-scope
Rectangle 27 204

You need to use $scope.$apply() if you want to make any changes to a scope value from outside the control of angularjs like a jquery/javascript event handler.

function change() {
    alert("a");
    var scope = angular.element($("#outer")).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    })
}

Thanks for the answer. I've tried the Fiddle you've attached but I still get the same "You are great" string even after I click on "click me". I get the alert, just not the string change. Are you seeing changes?

angular.element("#scope")
angular.element($("#scope"))

I know it been a while, but I hope some can answer me on this ... Why does var scope = angular.element($("#outer")).scope(); have to be declared inside the change function? If I move it to the global space it's a no go?

@MarcM. I think it has to do with Angular's scope recreation. By the time you're using the change function, the previous scope the global var was pointing to may no longer exist (due to the recreation).

AngularJS access scope from outside js function - Stack Overflow

angularjs angularjs-scope
Rectangle 27 73

The javascript you want to call from the child iframe needs to be in the head of the parent. If it is in the body, the script is not available in the global scope.

<head>
    <script>
    function abc() {
        alert("sss");
    }
    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="parent.abc();" href="#">Click Me</a>
    </iframe>
</body>

Hope this helps anyone that stumbles upon this issue again.

None of the techniques mentioned in this post work on Chrome. Any solutions for this?

If I remember correctly, I couldn't get this to work as expected if the iframe had a different domain to the parent. Sorry this isn't a solution, but it might explain why it isn't working.

Yes. I do know that it is because of different domains, but is there not a way to work this around?

I have just posted what might be a workaround to your problem. Take a look at the other answer.

So I have a domain something.com and my iframe is at something.something.com and I get a permission denied error. Shouldn't a subdomain be able to work?

javascript - Calling a parent window function from an iframe - Stack O...

javascript iframe onclick
Rectangle 27 9

window.alertTest = function () {
  alert("Testing");
};

...and calling it in the same way you have in the question ;-)

In a browser, everything in javascript is a child of the window object. When you define a function in the form function funcName() { ... } you are effectively defining a private method of the window object. This doesn't matter under normal circumstances, because all code is executed within the scope of window, so it has access to these private methods.

But when you try and access the window object from the outside (i.e. another window object, that of your iframe) you will not be allowed access to it. If you define the function in the form window.funcName = function () { ... }; you are creating a privileged method, that is accessible from the outside but also has access to the private methods and properties (i.e. the variables in the script), so it will work when you try and call it from your iframe.

Why is this not the accepted and most upvoted answer? It works like a charm and comes with an excellent explanation

Javascript: Calling function in parent from iframe - Stack Overflow

javascript function iframe parent
Rectangle 27 9

window.alertTest = function () {
  alert("Testing");
};

...and calling it in the same way you have in the question ;-)

In a browser, everything in javascript is a child of the window object. When you define a function in the form function funcName() { ... } you are effectively defining a private method of the window object. This doesn't matter under normal circumstances, because all code is executed within the scope of window, so it has access to these private methods.

But when you try and access the window object from the outside (i.e. another window object, that of your iframe) you will not be allowed access to it. If you define the function in the form window.funcName = function () { ... }; you are creating a privileged method, that is accessible from the outside but also has access to the private methods and properties (i.e. the variables in the script), so it will work when you try and call it from your iframe.

Why is this not the accepted and most upvoted answer? It works like a charm and comes with an excellent explanation

Javascript: Calling function in parent from iframe - Stack Overflow

javascript function iframe parent
Rectangle 27 2

Calling a method of a object

this is one of the misunderstood concept in JavaScript because it behaves little differently from place to place. Simply, this refers to the "owner" of the function we are currently executing.

this helps to get the current object (a.k.a. execution context) we work with. If you understand in which object the current function is getting executed, you can understand easily what current this is

var val = "window.val"

var obj = {
    val: "obj.val",
    innerMethod: function () {
        var val = "obj.val.inner",
            func = function () {
                var self = this;
                return self.val;
            };

        return func;
    },
    outerMethod: function(){
        return this.val;
    }
};

//This actually gets executed inside window object 
console.log(obj.innerMethod()()); //returns window.val

//Breakdown in to 2 lines explains this in detail
var _inn = obj.innerMethod();
console.log(_inn()); //returns window.val

console.log(obj.outerMethod()); //returns obj.val

Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.

var status = 1;
var helper = {
    status : 2,
    getStatus: function () {
        return this.status;
    }
};

var theStatus1 = helper.getStatus(); //line1
console.log(theStatus1); //2

var theStatus2 = helper.getStatus;
console.log(theStatus2()); //1

When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.

this
function Person(name){
    this.personName = name;
    this.sayHello = function(){
        return "Hello " + this.personName;
    }
}

var person1 = new Person('Scott');
console.log(person1.sayHello()); //Hello Scott

var person2 = new Person('Hugh');
var sayHelloP2 = person2.sayHello;
console.log(sayHelloP2()); //Hello undefined

When new Person() is executed, a completely new object is created. Person is called and its this is set to reference that new object.

function testFunc() {
    this.name = "Name";
    this.myCustomAttribute = "Custom Attribute";
    return this;
}

var whatIsThis = testFunc();
console.log(whatIsThis); //window

var whatIsThis2 = new testFunc();
console.log(whatIsThis2);  //testFunc() / object

console.log(window.myCustomAttribute); //Custom Attribute

If we miss new keyword, whatIsThis referes to the most global context it can find(window)

If the event handler is inline, this refers to global object

<script type="application/javascript">
    function click_handler() {
        alert(this); // alerts the window object
    }
</script>

<button id='thebutton' onclick='click_handler()'>Click me!</button>

When adding event handler through JavaScript, this refers to DOM element that generated the event.

  • You can also manipulate the context using .apply() .call() and .bind()
  • JQuery proxy is another way you can use to make sure this in a function will be the value you desire. (Check Understanding $.proxy(), jQuery.proxy() usage)

javascript - How does the "this" keyword work? - Stack Overflow

javascript this
Rectangle 27 2

Calling a method of a object

this is one of the misunderstood concept in JavaScript because it behaves little differently from place to place. Simply, this refers to the "owner" of the function we are currently executing.

this helps to get the current object (a.k.a. execution context) we work with. If you understand in which object the current function is getting executed, you can understand easily what current this is

var val = "window.val"

var obj = {
    val: "obj.val",
    innerMethod: function () {
        var val = "obj.val.inner",
            func = function () {
                var self = this;
                return self.val;
            };

        return func;
    },
    outerMethod: function(){
        return this.val;
    }
};

//This actually gets executed inside window object 
console.log(obj.innerMethod()()); //returns window.val

//Breakdown in to 2 lines explains this in detail
var _inn = obj.innerMethod();
console.log(_inn()); //returns window.val

console.log(obj.outerMethod()); //returns obj.val

Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.

var status = 1;
var helper = {
    status : 2,
    getStatus: function () {
        return this.status;
    }
};

var theStatus1 = helper.getStatus(); //line1
console.log(theStatus1); //2

var theStatus2 = helper.getStatus;
console.log(theStatus2()); //1

When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.

this
function Person(name){
    this.personName = name;
    this.sayHello = function(){
        return "Hello " + this.personName;
    }
}

var person1 = new Person('Scott');
console.log(person1.sayHello()); //Hello Scott

var person2 = new Person('Hugh');
var sayHelloP2 = person2.sayHello;
console.log(sayHelloP2()); //Hello undefined

When new Person() is executed, a completely new object is created. Person is called and its this is set to reference that new object.

function testFunc() {
    this.name = "Name";
    this.myCustomAttribute = "Custom Attribute";
    return this;
}

var whatIsThis = testFunc();
console.log(whatIsThis); //window

var whatIsThis2 = new testFunc();
console.log(whatIsThis2);  //testFunc() / object

console.log(window.myCustomAttribute); //Custom Attribute

If we miss new keyword, whatIsThis referes to the most global context it can find(window)

If the event handler is inline, this refers to global object

<script type="application/javascript">
    function click_handler() {
        alert(this); // alerts the window object
    }
</script>

<button id='thebutton' onclick='click_handler()'>Click me!</button>

When adding event handler through JavaScript, this refers to DOM element that generated the event.

  • You can also manipulate the context using .apply() .call() and .bind()
  • JQuery proxy is another way you can use to make sure this in a function will be the value you desire. (Check Understanding $.proxy(), jQuery.proxy() usage)

javascript - How does the "this" keyword work? - Stack Overflow

javascript this
Rectangle 27 2

Calling a method of a object

this is one of the misunderstood concept in JavaScript because it behaves little differently from place to place. Simply, this refers to the "owner" of the function we are currently executing.

this helps to get the current object (a.k.a. execution context) we work with. If you understand in which object the current function is getting executed, you can understand easily what current this is

var val = "window.val"

var obj = {
    val: "obj.val",
    innerMethod: function () {
        var val = "obj.val.inner",
            func = function () {
                var self = this;
                return self.val;
            };

        return func;
    },
    outerMethod: function(){
        return this.val;
    }
};

//This actually gets executed inside window object 
console.log(obj.innerMethod()()); //returns window.val

//Breakdown in to 2 lines explains this in detail
var _inn = obj.innerMethod();
console.log(_inn()); //returns window.val

console.log(obj.outerMethod()); //returns obj.val

Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.

var status = 1;
var helper = {
    status : 2,
    getStatus: function () {
        return this.status;
    }
};

var theStatus1 = helper.getStatus(); //line1
console.log(theStatus1); //2

var theStatus2 = helper.getStatus;
console.log(theStatus2()); //1

When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.

this
function Person(name){
    this.personName = name;
    this.sayHello = function(){
        return "Hello " + this.personName;
    }
}

var person1 = new Person('Scott');
console.log(person1.sayHello()); //Hello Scott

var person2 = new Person('Hugh');
var sayHelloP2 = person2.sayHello;
console.log(sayHelloP2()); //Hello undefined

When new Person() is executed, a completely new object is created. Person is called and its this is set to reference that new object.

function testFunc() {
    this.name = "Name";
    this.myCustomAttribute = "Custom Attribute";
    return this;
}

var whatIsThis = testFunc();
console.log(whatIsThis); //window

var whatIsThis2 = new testFunc();
console.log(whatIsThis2);  //testFunc() / object

console.log(window.myCustomAttribute); //Custom Attribute

If we miss new keyword, whatIsThis referes to the most global context it can find(window)

If the event handler is inline, this refers to global object

<script type="application/javascript">
    function click_handler() {
        alert(this); // alerts the window object
    }
</script>

<button id='thebutton' onclick='click_handler()'>Click me!</button>

When adding event handler through JavaScript, this refers to DOM element that generated the event.

  • You can also manipulate the context using .apply() .call() and .bind()
  • JQuery proxy is another way you can use to make sure this in a function will be the value you desire. (Check Understanding $.proxy(), jQuery.proxy() usage)

javascript - How does the "this" keyword work? - Stack Overflow

javascript this
Rectangle 27 270

angular.module('yourModuleName').directive('ngEnter', function() {
        return function(scope, element, attrs) {
            element.bind("keydown keypress", function(event) {
                if(event.which === 13) {
                    scope.$apply(function(){
                        scope.$eval(attrs.ngEnter, {'event': event});
                    });

                    event.preventDefault();
                }
            });
        };
    });
<div ng-app="" ng-controller="MainCtrl">
    <input type="text" ng-enter="doSomething()">    
</div>

Is there a clever way to get this to trigger any time they hit enter while on your page?

@EpokK I wanna disable the enter key for the entire form, how can I do that? (I want to avoid form submission with enter)

very nice, but as per AngularJs' reccomendation, you shouldn't create directives, services, or filters that are prefixed with ng-, in case an official release later uses the same name.

Great solution. I just changed the name to keyBind and this line "if(event.which === 13) {" to this "if(event.which === Number(attrs.key)) {" And then my input to "<input type="text" bind-key="doSomething()" key="13">" so that I could re-use it for different key events.

IMPORTANT: Adding both the keydown and keypress events without a comma to delimit them means both may fire simultaneously. This is likely to spawn $rootScope:inprog errors. Adding a comma between them creates a disjunctive, and ensures only only $digest cycle occurs. Couldn't apply the edit since it's only a single character.

function - Submit form on pressing Enter with AngularJS - Stack Overfl...

function angularjs call keypress enter
Rectangle 27 270

angular.module('yourModuleName').directive('ngEnter', function() {
        return function(scope, element, attrs) {
            element.bind("keydown keypress", function(event) {
                if(event.which === 13) {
                    scope.$apply(function(){
                        scope.$eval(attrs.ngEnter, {'event': event});
                    });

                    event.preventDefault();
                }
            });
        };
    });
<div ng-app="" ng-controller="MainCtrl">
    <input type="text" ng-enter="doSomething()">    
</div>

Is there a clever way to get this to trigger any time they hit enter while on your page?

@EpokK I wanna disable the enter key for the entire form, how can I do that? (I want to avoid form submission with enter)

very nice, but as per AngularJs' reccomendation, you shouldn't create directives, services, or filters that are prefixed with ng-, in case an official release later uses the same name.

Great solution. I just changed the name to keyBind and this line "if(event.which === 13) {" to this "if(event.which === Number(attrs.key)) {" And then my input to "<input type="text" bind-key="doSomething()" key="13">" so that I could re-use it for different key events.

IMPORTANT: Adding both the keydown and keypress events without a comma to delimit them means both may fire simultaneously. This is likely to spawn $rootScope:inprog errors. Adding a comma between them creates a disjunctive, and ensures only only $digest cycle occurs. Couldn't apply the edit since it's only a single character.

function - Submit form on pressing Enter with AngularJS - Stack Overfl...

function angularjs call keypress enter
Rectangle 27 980

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behaviour as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMAScript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behaviour they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

Great answer but consider adding an additional optional solution which is just to not use classes, new, or this at all.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 970

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behaviour as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMAScript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behaviour they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

Great answer but consider adding an additional optional solution which is just to not use classes, new, or this at all.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 954

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this, because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMASCript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback / event handler. Functions are first class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

Great answer but consider adding an additional optional solution which is just to not use classes, new, or this at all.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 936

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this, because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMASCript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback / event handler. Functions are first class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

Hey, any chance you'd add a section on the ES7 :: bind syntax proposal, or would you prefer to wait until it's more finalized than not?

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 901

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this, because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMASCript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback / event handler. Functions are first class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

Hey, any chance you'd add a section on the ES7 :: bind syntax proposal, or would you prefer to wait until it's more finalized than not?

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 900

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this, because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMASCript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback / event handler. Functions are first class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

Hey, any chance you'd add a section on the ES7 :: bind syntax proposal, or would you prefer to wait until it's more finalized than not?

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 898

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this, because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMASCript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback / event handler. Functions are first class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

Hey, any chance you'd add a section on the ES7 :: bind syntax proposal, or would you prefer to wait until it's more finalized than not?

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 897

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this, because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMASCript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback / event handler. Functions are first class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

Hey, any chance you'd add a section on the ES7 :: bind syntax proposal, or would you prefer to wait until it's more finalized than not?

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 121

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    }
    return n * myself(n-1);
}
typeof myself === 'undefined'
myself

visible only inside of the function

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

arguments.callee
var factorial = function (n) {
    if (n <= 1) {
        return 1;
    }
    return n * arguments.callee(n-1);
}

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

+1 Although it's a little buggy in IE8 and lower in that myself is actually visible in the enclosing variable environment, and it references a duplicate of the actual myself function. You should be able to set the outer reference to null though.

Thanks for the answer! Both were helpful and solved the problem, in 2 different ways. In the end I randomly decided which to accept :P

just for me to understand. What is the reason behind multiplying the function on each return? return n * myself(n-1); ?

Calling a javascript function recursively - Stack Overflow

javascript function recursion function-expression