JAVASCRIPT

VANILLA  #4

ANDREI PFEIFFER


Scope   Context

SCOPE  !==  CONTEXT

    

            // global scope
            var x = 10;

            function foo() {
                // foo scope

                function bar() {
                    // bar scope
                    var y = 30;
                }
            }



Scope

is a "block OF CODE"

SCOPE

refers to variable visibility

SCOPE

is static / lexical

SCOPE

RElates TO function definition

Context

relates to function calls

CONTEXT

IS AN OBJECT

CONTEXT

IS this

Execution CONTEXT

Global, Function, Eval

Code

LexicalVARIABLE

Environments

ThisBinding

Scope = variables


Context = this


Execution Context = Scope + Context

this

Function

    

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

            foo();

            // global [Object]



Function

    

            function foo() {
                'use strict';

                console.log( this );
            }

            foo();

            // undefined



Constructor

    

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

            var o = new Foo();

            // o [Object]



Method

    

            var o = {
                foo: function() {
                    console.log( this );
                }
            };

            o.foo();

            // o [Object]



Call, Apply

    

            var o = {
                name: "aaa",
                foo: function(x, y) {
                    console.log( this );
                }
            };

            var o2 = { name: "bbb" };

            o.foo.call( o2 );
            // o2 [Object]

Bind

    

            var o = {
                foo: function() {
                    console.log( this );
                }
            };

            var o2  = {},
                bar = o.foo.bind( o2 );

            bar();
            // o2 [Object]

a little bit of

code

Q&A

Thank You

JavaScript Vanilla #4 - Scope & Context

By Andrei Pfeiffer

JavaScript Vanilla #4 - Scope & Context

This forth part of the series focuses on the difference between 2 terms that are somewhat confusing even to intermediate users: "scope" and "context".

  • 963