this in JavaScript

The this keyword is one of the most misunderstood and confusing aspect in JavaScript. This has a completely different meaning in JavaScript than in most other programming languages. Because programmers try to apply the meaning of other programming languages to JavaScript, this often results in great confusion. To understand this, however, you have to put aside all known concepts from other programming languages. This in Javascript has nothing to do with classes or their instantiation or similar concepts from other programming languages.

Every function, while executing, has a reference to its current execution context, called this.

In JavaScript, this is a reference to its current execution context, i.e. this is given by the call site (location in code where the function is called).  What this means exactly, is further discussed below.

Let me give a first example:


function foo(){
console.log(this.bar);
}
var bar="bar1";
foo(); // bar1

If you are not in strict mode default the this keyword to the global object. Since the variable is cash in the global object is this.bar equal „bar“. However, if you are in strict mode, to Uncaught TypeError: Can not read property ‚bar‘ of undefined is thrown. In strict mode, this is the undefined value.

Above The example has been extended with an Object o1. If the o1.foo () method is called the current execution context is to o1. Thus „bar2“ output. This is called implicit binding.


function foo(){
console.log(this.bar);
}
var o1 = {
bar: "bar2",
foo: function() { console.log(this.bar);}
};
var bar="bar1";
foo(); // bar1
o1.foo(); // bar2

call, apply, bind
bind: use it if you want to be predictable
############ EXAMPLE ############

new
############ EXAMPLE ############
Kyle Simpsons summarizes these facts in his book „You don’t know Javascript“ under 4 rules in order of precednece:

4 rules in order of precedence to never be again confues about the this keyword:

was the function called with new?
was the function called with call or apply specifing an excplicit this?
was the function called via a conaining/owning object(context)?
default: global object (except strict mode)

ECMAScript 6 hat arrow Funktionen eingeführt. Dort verhält sich this nochmals ein wenig spezieller wie folgendes Beispiel zeigt:

arrow functions: we get the context where the code is running
you can not bind a new object to an arrow function. the javascript does even throw an error, it just ignores the bind. call, bind and apply are all useless when using arrow functions. You can not change the this context when using arrwo functions.

this

Unbenannt

 

Werbung

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s