The 'this' keyword (Part 1)
Ariel Isaac M.

Highlights
- Powerful keyword
- Extremly hard to use
- Not an empirical knowledge
First of all

Let's get started!! (And confused)
console.log( this === window );
function test(){
console.log( this === window);
}
test();
var myApp = {
name : 'Archer',
lastName : 'Sterling',
completeName : this.name + this.lastName
}
console.log( myApp.completeName );
Fixed
var myApp = {
name : 'Archer',
lastName : 'Sterling',
completeName : function(){
return this.name + ' ' + this.lastName;
}
}
console.log( myApp.completeName() );
Invoke via function
var name="Strange World";
var myApp = function(){
var name = "World"
var sayHello = function(){
console.log( 'Hello, ' + this.name );
};
sayHello();
};
myApp();
Why this?
- It's all about the ownership
- What does this refer to in the function doSomething()?
var person = {
firstName: "John",
lastName: "Doe",
fullName: function doSomething() {
console.log(this.firstName + " " + this.lastName);
console.log(person.firstName + " " + person.lastName);
}
}
person.fullName();
var person = {
firstName :"John",
lastName :"Doe",
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
}
person.showFullName ();
var anotherPerson = {
firstName :"Isaac",
lastName :"Schneider"
};
person.showFullName.apply (anotherPerson);
apply() and call();
function identify() {
return this.name.toUpperCase();
}
function speak() {
var greeting = "Hello, I'm " + identify.call( this );
console.log( greeting );
}
var me = {
name: "Ariel"
};
var you = {
name: "Luis"
};
identify.call( me ); // ARIEL
identify.apply( you ); // LUIS
speak.call( me ); // Hello, I'm Ariel
speak.apply( you ); // Hello, I'm Luis
function theFunction(name, profession, age) {
console.log("My name is " + name + " I am a " + profession + " and I am "+age+ " old.");
}
theFunction("John", "fireman",33);
theFunction.apply(undefined,["Slim Shady", "Rapper","30"]);
theFunction.call("Claude","Hobbo", "25");
This... itself?
- Reasonable grammatical inference
- Everything is an object!!
- "Nothing is true everything is permitted"
function foo(num) {
console.log( "foo: " + num );
this.count++;
}
foo.count = 0;
var i;
for (i=0; i<10; i++) {
if (i > 5) {
foo( i );
}
}
console.log( foo.count );
Under the scope
- ' var ' Importance
- Within the scope
- Dangerous issue
var a = 1, b = 2, c = 3;
function alphabet(str){
var a = 'A', b = 'B'
c = 'C', d = 'D';
return str + ' ' + a + b + c + '…';
}
console.log( alphabet("Let's say the alphabet!") );
console.log(a, b, c);
That's all folks, Thanks!!
The this keyword Monday Talks (16/02/2015)
By Ariel Isaac
The this keyword Monday Talks (16/02/2015)
- 9