vef1-2025

Vefforritun 1 kennd haustið 2025

View the Project on GitHub vefforritun/vef1-2025

Fyrirlestur – Hlutir

Vefforritun 1 — TÖL107G

Ólafur Sverrir Kjartansson, osk@hi.is


Hlutir og hjúpun


Methods


this


function logThis() { console.log(this); }
const Obj = {
  logThis() { console.log(this); },
};
const btn = document.querySelector('button');
btn.addEventListener('click', logThis);

console.log(this); // window
logThis(); // window
Obj.logThis(); // {logThis: f}
btn.click(); // <button>


const rabbit = {
  type: 'the',
};
rabbit.speak = (line) => {
  console.log(
    `${this.type} rabbit says '${line}'`
  );
};

rabbit.speak('I’m alive.');
// → undefined rabbit says 'I’m alive.'

const rabbit = {
  type: 'the',
  speak(line) {
    console.log(
      `${this.type} rabbit says '${line}'`
    );
  }
};

rabbit.speak('I’m alive.');
// → the rabbit says 'I’m alive.'

Apply & call


function speak(line) {
  console.log(
    `${this.type} rabbit says ${line}`
  );
}
//  festum fallið á hlutinn 👇
const old = { type: 'old', speak };
const hungy = { type: 'hungry', speak };

old.speak('Oh my');
// old rabbit says Oh my
hungy.speak('I could use a carrot');
// hungry rabbit says I could use a carrot

function speak(line) {
  console.log(
    `${this.type} rabbit says ${line}`
  );
}

const old = { type: 'old' };

//    👇  köllum í fallið _með_ hlutnum
speak.apply(old, ['Oh my']);
// old rabbit says Oh my
speak.call({ type: 'hungry' }, 'Yum');
// hungry rabbit says Yum

Bind


Bind – dæmi

function speak(line) {
  console.log(
    `${this.type} rabbit says ${line}`
  );
}
const blueRabbit = { type: 'blue' };

// bindum fall v/hlut 👇 fáum nýtt fall!
const bound = speak.bind(blueRabbit);
bound('hi'); // blue rabbit says hi
// Getum kallað strax í fall 👇
speak.bind(blueRabbit, 'bye')();
// blue rabbit says bye

Arrow föll


function normalize() {
  function inner(n) {
    //          👇 vísar í window! 🙀
    return n / this.length;
  }
  //           👇 vísar í „réttan“ hlut 🥴
  console.log(this.coords.map(inner));
}

const o = { coords: [0, 2, 3], length: 5 };

normalize.call(o);
// → [NaN, Infinity, Infinity]

function normalize() {
  console.log(
    // 👇 vísar í réttan hlut
    this.coords.map(
      //        👇 vísar í réttan hlut
      n => n / this.length
    )
  );
}

const o = { coords: [0, 2, 3], length: 5 };

normalize.call(o);
// → [0, 0.4, 0.6]

function normalize() {
  const inner = (n) => {
    //          👇 vísar í réttan hlut 😊
    return n / this.length;
  }
  console.log(this.coords.map(inner));
}

const o = { coords: [0, 2, 3], length: 5 };

normalize.call(o);
// → [0, 0.4, 0.6]

Prótótýpur



const empty = {};
console.log(empty.toString);
// → function toString() { … }
console.log(empty.toString());
// → [object Object]
console.log(1.toString()); // → "1"
console.log(NaN.toString()); // → "NaN"
console.log(null.toString());
// → TypeError: null has no properties

Aðrar prótótýpur


const empty = Object.getPrototypeOf({});
console.log(
  empty === Object.prototype
);
// → true
console.log(
  Object.getPrototypeOf(Object.prototype)
);
// → null

const funcProto = Object.getPrototypeOf(
  Math.max
);

console.log(
  funcProto === Function.prototype
);
// → true
console.log(
  Object.getPrototypeOf(funcProto) ===
    Object.prototype
);
// → true

const array = Object.getPrototypeOf([]);

console.log(
  array === Array.prototype
);
// → true

const objProto = Object.getPrototypeOf({});
console.log(
  Object.getPrototypeOf(objProto)
);
// → null
// keðjan endar á Object prototype!

Prótótýpu keðjan



Hlutir með ákveðna prótótýpu


const protoRabbit = {
  speak(line) {
    console.log(
      `${this.type} rabbit says '${line}'`
    );
  }
};
const killer = Object.create(protoRabbit);
killer.type = 'killer';
//    👇 speak fall kemur frá prototype
killer.speak('SKREEEE!');
// → killer rabbit says 'SKREEEE!'

Klasar (classes)



Smiðir og new


function Rabbit(type) {
  this.type = type;
}
Rabbit.prototype.speak = function (line) {
  console.log(
    `The ${this.type} rabbit says ${line}`
  );
};
const weirdRabbit = new Rabbit('weird');
console.log(weirdRabbit);
// Rabbit {type: "weird"}
weirdRabbit.speak('🐰');
// The weird rabbit says '🐰'

Yfirskrifuð eigindi


Rabbit.prototype.teeth = 'small';
const killerRabbit = new Rabbit('killer');
console.log(killerRabbit.teeth);
// → small
killerRabbit.teeth = 'long, sharp, bloody';
console.log(killerRabbit.teeth);
// → long, sharp, and bloody

Erfðir á rabbits


function Rabbit(type) {
  this.type = type;
}

const fooRabbit = new Rabbit('foo');
console.log(fooRabbit.toString());
// "[object Object]"

Rabbit.prototype.toString = function () {
  return `Rabbit of type ${this.type}`;
};

console.log(fooRabbit.toString());
// "Rabbit of type foo"

Classes


class Rabbit {
  constructor(type) {
    this.type = type;
  }
  speak(line) {
    console.log(
      `${this.type} rabbit says '${line}'`
    );
  }
  toString() {
    return `Rabbit of type ${this.type}`;
  }
}

const killerRabbit = new Rabbit('killer');

class Foo {
  constructor(name) {
    this._name = name;
  }

  hi() { return 'hi!'; }

  static bar() { return 1; }

  get name() { return this._name; }

  set name(value) { this._name = value; }
}

const foo = new Foo('Asdf');
foo.hi(); // "hi!"
foo.name = 'bar';
foo.name; // "bar"

Foo.bar(); // 1