0
0
Javascriptprogramming~10 mins

this in functions in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to log the value of this.name inside the function.

Javascript
const obj = { name: 'Alice', greet: function() { console.log(this[1]name); } };
obj.greet();
Drag options to blanks, or click blank then click option'
A.
B->
C::
D,
Attempts:
3 left
💡 Hint
Common Mistakes
Using arrow (->) or double colon (::) instead of dot.
Forgetting to use any operator between this and name.
2fill in blank
medium

Complete the code to correctly bind this inside the function using bind.

Javascript
const obj = { value: 42 };
function show() { console.log(this.value); }
const boundShow = show[1](obj);
boundShow();
Drag options to blanks, or click blank then click option'
A.set
B.call
C.bind
D.apply
Attempts:
3 left
💡 Hint
Common Mistakes
Using call or apply which invoke the function immediately.
Using a non-existent method like set.
3fill in blank
hard

Fix the error in the arrow function to correctly log this.name from the object.

Javascript
const person = {
  name: 'Bob',
  greet: () => { console.log(this[1]name); }
};
person.greet();
Drag options to blanks, or click blank then click option'
A,
B->
C::
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using arrow functions when needing object this.
Using wrong operators instead of dot.
4fill in blank
hard

Fill both blanks to create a method that returns a function which logs this.count correctly.

Javascript
const counter = {
  count: 0,
  getIncrementer: function() {
    return function() { console.log(this[1]count); }.[2](this);
  }
};
const inc = counter.getIncrementer();
inc();
Drag options to blanks, or click blank then click option'
A.
B.call
C.bind
D.apply
Attempts:
3 left
💡 Hint
Common Mistakes
Using bind which returns a new function instead of invoking immediately.
Forgetting to bind or call this so this.count is undefined.
5fill in blank
hard

Fill all three blanks to create an object method that uses an arrow function to log this.message after 1 second.

Javascript
const notifier = {
  message: 'Hello!',
  notify: function() {
    setTimeout(() => { console.log(this[1]message); }, [2]);
  },
  delay: [3]
};
notifier.notify();
Drag options to blanks, or click blank then click option'
A.
B1000
C500
D2000
Attempts:
3 left
💡 Hint
Common Mistakes
Using a regular function inside setTimeout which changes this.
Using wrong delay time or forgetting the dot operator.