THIS

and

PROTOTYPE

this is it

Your calling context

Basic calling context example

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

bar();

Member calling context

var foo = {};

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

foo.bar = bar;
foo.bar();

why calling context is awesome?

var foo = {
    bar: 123,
    bas: function () {
        console.log('inside this.bar is:', this.bar);
    }
}

foo.bas();

Unconfuse

Function.prototype

vs.

[[prototype]] i.e. __proto__

prototype

function Foo() { }

console.log(Foo.prototype);

console.log(Foo.prototype.constructor === Foo);

__proto__

var foo = {
    __proto__: {
        __proto__: {
            __proto__: {
                bar: 123
            }
        }
    }
};

console.log(foo.bar);

protoype and __proto__

function Foo() { }

var foo = new Foo();

console.log(foo.__proto__ === Foo.prototype);

why prototype is awesome?

function Foo() {}
Foo.prototype.log = function() {
    console.log('log');
}

var a = new Foo();
var b = new Foo();

a.log();
b.log();

Constructor

I new this

new and this

new and this

function Foo() {
    this.bar = 123;
    console.log('Is this global?: ', this == window);
}

// without the new operator
Foo();
console.log(window.bar);

// with the new operator
var newFoo = new Foo();
console.log(newFoo.bar);

Basic Class Structure

function Foo(val) {
    this.val = val;
}
Foo.prototype.log = function() {
    console.log(this.val);
}


var a = new Foo(1);
var b = new Foo(2);

a.log();
b.log();

Passing functions references

bind

why calling context is bad?

var foo = {
    bar: 123,
    bas: function () {
        console.log('inside this.bar is:', this.bar);
    }
}

var bas = foo.bas;
bas();

bind this

var foo = {
    bar: 123,
    bas: function () {
        console.log('inside this.bar is:', this.bar);
    }
}

var bas = foo.bas.bind(foo);
bas();

remove the middleman

call

I'll call it myself

var foo = {
    bar: 123,
};

function bas() {
    console.log('inside this.bar is:', this.bar);
}

bas.call(foo);

Call with arguments

var foo = {
    bar: 123,
};

function bas(a, b) {
    console.log('inside: this.bar(%d), a(%d), b(%d)', this.bar, a, b);
}

bas.call(foo, 1, 2);

Inheritance

Its __proto__ all the way down

101 chain

function Animal() { }
Animal.prototype.walk = function () { console.log('walk') };

function Bird() { }
Bird.prototype.__proto__ = Animal.prototype;
Bird.prototype.fly = function () { console.log('fly') };

var animal = new Animal();
animal.walk();

var bird = new Bird();
bird.walk();
bird.fly();

Parent member properties

Inheritance in native objects

Simple check for inheritance

Summary of this

Calling context

great for mixins

great for prototype

Constructor?

new

Summary of this

Passing a function reference?

bind

Calling a parent?

call

Intercepting?

apply

this-and-prototype

By basarat

this-and-prototype

  • 1,382