this keyword in javascript code example

Example 1: this keyword in javascript medium

For All Regular function, this points to the WINDOW Object ( Global Context ) .

Example 2: use of this keyword in js

The JavaScript this keyword refers to the object it belongs to. 
It has different values depending on where it is used: In a method, 
this refers to the owner object. Alone, this refers to the global 
object.

Example 3: javascript this

// In web browsers, the window object is also the global object:
console.log(this === window); // true

a = 37;
console.log(window.a); // 37

this.b = "MDN";
console.log(window.b)  // "MDN"
console.log(b)         // "MDN"

Example 4: new keyword in js

**Important Points** 

1.It creates a new object. The type of this object is object.
2.It sets this new object's internal, inaccessible, [[prototype]] (i.e. __proto__) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
3.It makes the this variable point to the newly created object.
4.It executes the constructor function, using the newly created object whenever this is mentioned.
5.It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.
Note: constructor function refers to the function after the new keyword, as in

new ConstructorFunction(arg1, arg2)

Example 5: js this in object

var wF = {
    w : 560,
    h : function() { return (312 - 42) / (560 / this.w) + 42; }
};

alert(wF.h())

Example 6: javascript this = that

var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
    // this is a reference to the element clicked on

    var that = this;

    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});

Tags:

Php Example