Classes Flashcards
Accessor properties are represented by what methods?
getter & setter
In an object literal, getter and setter are denoted by?
get & set
What does getter do?
Getter binds an object property to a function which is called when it’s looked up
What does setter do?
Setter bind an object property to a function which is called when someone tries to set it
What is the basic “class” syntax?
class MyClass {
constructor() {…};
method1() {…};
method2() {…};
}
What do you need to use in order to create a new object in class with all the listed methods?
new MyClass()
What happens inside “class” if you call the ‘new’
constructor() is automatically called inside “class” which means we can initialize the object there
What do you put between class methods?
Nothing!
Where does “class” store its methods? (e.g class MyClass())
In MyClass.prototype
What type is class? More precisely?
Function, more precisely the constructor method
// class is a function
alert(typeof User); // function
// …or, more precisely, the constructor method
alert(User === User.prototype.constructor); // true
What are the three differences between classes and constructors?
- Function created by class is labelled by a special internal property [[IsClassConstructor]]
- Class methods are non-enumerable
- Classes always “use strict”
What is a “class field”?
Syntax that allows you to add any property
What is the difference between a “class field” and methods inside class? (e.g class User())
Class field are set on individual objects, not on User.prototype
What are the two ways to bind inside class functions? (syntax)
- Pass a wrapper-function such as
setTimeout(function() {
user.sayHi(); // Hello, John!
}, 1000); - The class field “click” is created on a per-object basis, there’s a separate function for each Button object, with this inside it referencing that object. We can pass button.click around anywhere, and the value of this will always be correct.
class Button {
constructor(value) {
this.value = value;
}
click = () => {
alert(this.value);
}
}
let button = new Button(“hello”);
setTimeout(button.click, 1000); // hello
What is an important difference between class declaration and function declaration?
To call function, it doesn’t matter whether the function has been written before or after but classes MUST be defined before they are constructed