Keyword 'this'
You can refer to the attributes not only outside the class but inside, too, for example, inside methods. To do that, use this
keyword. this
is like a name of object, but it means the current object, i. e. it refers to the global object.
Let's change current age of the student each time we call happyBirthday()
function, and print it:
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Student{
name = 'June';
university = 'MIT';
age = 18;
gpa;
sleep(){
console.log('I am sleeping right now!')
}
happyBirthday(){
this.age += 1;
console.log('Today is my birthday! I am', this.age, 'yrs old!');
}
}
123456789101112131415class Student{ name = 'June'; university = 'MIT'; age = 18; gpa; sleep(){ console.log('I am sleeping right now!') } happyBirthday(){ this.age += 1; console.log('Today is my birthday! I am', this.age, 'yrs old!'); } }
Compito
Swipe to start coding
Modify happyBirthday()
function: output info about new age and about name of the student. After that, create an object of class Student
, and call this method three times to see what happens with age.
Soluzione
9
1
2
3
4
happyBirthday(){
this.age += 1;
console.log('I am', this.name, '. Today is my birthday! I am', this.age, 'yrs old!');
}
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 1. Capitolo 5
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Student{
name = 'June';
university = 'MIT';
age = 18;
gpa;
sleep(){
console.log('I am sleeping right now!')
}
happyBirthday(){
this.age += 1;
console.log('Today is my birthday');
}
}
// create an object and call the method three times
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione