Vefforritun 1 kennd haustið 2025
thisthisthis hagar sér öðruvísi í JavaScript en í öðrum málumthis global hluturinn, þ.e. þar sem allt er geymt (í browser window)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.'
thisapply – köllum í fall með gefnu this og fylki af argumentscall – köllum í fall með gefnu this og lista af argumentsfunction 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
this fyrir föllthis erfunction 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
thisthis er skilgreint eins og það var skilgreint í scope kringum fallfunction 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]
null og undefinedObject
Object.prototypeObject.getPrototypeOf() skilar hvaða prótótýpu gildi hefurconst 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
[] hefur Array.prototypeFunction.prototypeconst 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!
undefined skilaðObject.create() býr til hlut með ákveðinni prótótýpuconst 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!'
new og tilgreinum fall búum við til nýjan hlut þar sem this bendir á hlutinnthis sem hlut vegna new ef engu er skilað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 '🐰'
toString() til að skila sértæku gildi fyrir okkar hlutRabbit.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
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"
class skilgreintextends, constructor, super, static og getters og settersclass 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