Javascript

this & Object prototypes

Contents

  • What is this and what is not
  • Object
  • prototype
  • Inheritance in JS

Why we need this?

  • Avoid passing context to functions
  • Use same function with different contexts (DRY)
function increment() {
    this.count++;
}

What this is not

  • function itself
  • lexical scope
  • author-time binding

What this is

  • run-time binding
  • binding of how function is called

call-site

  • Not where function is declared
  • Location of function is invoked

bindings

  • default binding
  • implicit binding
  • explicit binding
  • new binding
function iHaveAThis () {
    console.log(this.a);
}

var obj = {
    a: 3,
    foo: iHaveAThis
}

// default binding
iHaveAThis();

// implicit binding
obj.foo();

// explicit binding
iHaveAThis.call(obj);

// new binding
function classish (a) {
    this.a = a;
}
var classLike = new classish(3);
console.log(classLike.a) // prints 3

What is this?

Precedence

  • Called with new binding?
    • newly constructed object
  • Called with call, apply, bind (explicit binding)?
    • Explicitly specified object
  • Called with context of an object (implicit binding)?
    • that context object
  • Default binding?
    • global or window object

ps: Lexical this

  • ES6 => arrow function
  • Adopts this lexically (author-time)
var obj = {a : 3};

function delay (ms) {
    setTimeout(() => {
        console.log(this.a);
    }, ms);
}

delay.apply(obj, 2000);

Always look the object where function is called, before dot!!

Before the moving objects

it's demo time

primitives

  • string
  • number
  • boolean
  • undefined
  • null
  • object

built-in objects

  • String
  • Number
  • Boolean
  • Object
  • Function
  • Array
  • Date
  • RegExp
  • Error

Objects

  • have properties
  • property descriptors
    • value,writable, configurable, enumerable
  • have getter and setter
  • details: Object@MDN

Classes in JS

  • Actually there's NO class
  • Even though class keyword in ES6, its syntatic sugar
  • Class means copying behaviour to instance
  • In JS, behaviours not copied between objects

prototype

  • internal property of objects
  • reference to another object
  • Prototype chain
    • property look-up
  • objects linked to common object's prototype instead of instances
  • prototypical inheritance

Behaviour Delegation

  • If child don't have a value or method, delegates to parent's (linked object) prototype
  • Prevents copying same functions for all instances

If it's confusing, we'll continue to dig up Javascript

Javascript - this & Object prototypes

By Özgün Bal

Javascript - this & Object prototypes

  • 97