Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions submissions/MisamKamal/assignment8.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Task 1: Fix the Lost Context
// You’re building a blog editor. The editor object has a method to return the title in uppercase.
const editor = {
title: 'my first blog',
getUpperTitle() {
return this.title.toUpperCase();
}
};
const getTitle = editor.getUpperTitle.bind(editor);
console.log(getTitle());

// ************************************************************************************************************************************
// Task 2: Arrow or Regular?
// You have a form handler object that tracks user input:
const formHandler = {
value: 'initial',
onChange(newValue) {
this.value = newValue;
}
};

function simulateInputChange(callback) {
callback('updated');
}

simulateInputChange(formHandler.onChange);

// ❓ Now log formHandler.value
console.log(formHandler.value);

// Your Tasks:

// Predict what formHandler.value will be.
// The predicted value is 'initial', because simulateInputChange calls onChange and tries to set the new value to 'updated',
// but it does so without specifying which object this should refer to.
// As a result, this inside onChange does not refer to formHandler, so the original value does not change.

// Fix the bug using either .bind() or an arrow function (your choice).
simulateInputChange(formHandler.onChange.bind(formHandler));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could u please use arrow function as another solution here? and explain why it could work

console.log(formHandler.value);

// Explain which fix you used and why.
// "I used .bind() and passed formHandler to it. This is because using .bind(formHandler) forces the this inside the onChange method to always refer to the formHandler object,
// which ensures that the value is updated correctly.

// ************************************************************************************************************************************

// Task 3: Method Extraction Issue
// You’re developing a translation tool. The following object works well, but fails when methods are passed around.

const translator = {
language: 'Arabic',
getLanguage() {
return `Current language: ${this.language}`;
}
};

// ❓ Write a function logLanguageInfo(getter) that logs the language info correctly even if getLanguage is passed as an argument.
function logLanguageInfo(getter){
console.log(getter.call(translator));

}
logLanguageInfo(translator.getLanguage);