Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 81 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 82 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 81 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 82 Javascript ‘this’ | Sveitech

Javascript ‘this’

// In the global scope, the 'this' keyword points to the global object.
var global = this;

// In browsers, the 'window' object is the global object.
console.log(this === window);            // true
console.log(this.document === document); // true

// In nodejs, the global object is called 'global'
console.log(this === global);            // true

// 'this' behaves differently inside functions, depending on
// how the function is called.

// Calling a global function, leaves 'this' untouched, and
// it still points to the global object
function foo() {
    return this;
};

foo() === window; // true. Or foo() === global for nodejs

// Calling a function as a member function of an object,
// will assign the object to 'this' when entering the
// function
var object = {
    foo: function() {
        return this;
    }
};

object.foo() === object; // true

// 'this' is assigned to the current object used as caller,
// even when going through the prototype chain. If a member
// is found in a parent object (prototype lookup), 'this'
// still refers to the original object trying to access the
// member.
var base = {foo: function() { return this; }};
var parent = Object.create(base);

parent.foo() === parent; // true
base.foo() === base;     // true

Sveistrup Technologies