Sind Klassen in Javascript so wie Klassen in anderen Sprachen?
-Nein
Sind Klassen in Javascript nativ vorhanden?
- Sie sind Constructors und Prototypes
Ist Javascript eine native Objektorientierte Sprache OOP?
-Nein, mit ES6 wurden Klassen nur sehr vereinfacht
Was sind Klassen in Javascript?
- Spezielle Funktionen (Wie Arrow Functions besonders sind)
Wie richtet man eine Klasse ein?
clas Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}const newRect = new Rectangle(400, 800);
Was macht die Constructor Function in einer Class?
- Alle direkten Attribute/Properties werden im Constructor gesetzt
Muss man sowas wie Parent.call(this, bananaAttrs) mit Classes noch verwenden?
-Nein, braucht man nie wieder
Was macht die extends Methode?
-Ersetzte das .call(this, someAttrs); in Zukunft
was macht die super() Function?
-Ersetzte jegliche andere bishere Syntax um Objects und Prototypes zu verbinden
Sind Klassen nur Funktionen?
-JA!
Erkläre die Klasse:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(this.name + ' barks.');
}
}Was macht super ()?
-Gibt die Attribute an die Oberklasse weiter
Wenn man eine Klasse extended muss man super() benutzen?
Ja, sonst erhält man keinen Zugang zu den Attributen!
Gebe ein Beispiel einer Class an:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(this.name + ' meows.');
}
}
}
const sascha = new Dog(‘Sascha’);
coinsole. log(sascha );
sascha. speak(); //funktioniert, weil durch die Inheritance die speak() Methode reachable is
const thiara= new Cat('Thiara');
thiara.speak(); //thiara meows because she overrides the base methodWas für Vorteile bieten Klassen?
Wie wandelt man diese Person Constructor Function in eine Person class um?
function persin(attributes) {
this.age = attributes.age;
this.name = attributes.name;
this.homeTown = attributes.homeTown;
}Person.prototype.speak = function () {
return Hello, my name is $[this.name};
};
class Person {
constructor(attributes) {
this.age = attributes.age;
this.name = attributes.name;
this.homeTown = attributes.homeTown;
}
speak() {
return `Hello, my name is $[this.name}`;
}
}Wie sieht eine Klasse mit super() und neuen Attributen aus?
class Child extends Parent {
construcotr(childAttrs) {
super(childAttrs); //THIS IS IMPORTANT
this.isChild = childAttrs.isChild; //UNIQUE ATTRIBUTE
}
checkIfChild() {
if(this.isChild) {
console.log(this.speak+ ' and I am a child object.');
}
}