From 693232390e6d8a7e4b32289a7f348b1684ba4537 Mon Sep 17 00:00:00 2001 From: poralla chandu <121390022+Chanduporalla@users.noreply.github.com> Date: Fri, 18 Oct 2024 20:36:16 +0530 Subject: [PATCH] Update README.md The code assigns a function to a variable, which causes it to lose its original context. This results in the this keyword referring to the global object when the function is called, leading to an undefined name. To preserve the original context, use bind to create a new function with a specific this value. --- README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/README.md b/README.md index b203a060..37d8d27a 100644 --- a/README.md +++ b/README.md @@ -5149,3 +5149,32 @@ The condition within the `if` statement checks whether the value of `!typeof ran

+profile picture + + +###### 155. What's the output? + +```javascript +const obj = { + name: "John", + age: 30, + greet: function() { + console.log("Hello, my name is " + this.name); + } +}; + +const greetFunction = obj.greet; +greetFunction();What will be the output of this code? + + -A: A. Hello, my name is John + -B: B. Hello, my name is undefined + -C:C. TypeError: Cannot read property 'name' of undefined + -D:D. The code will result in an error. +Explanation: + +The correct answer is B. + +In JavaScript, when a function is assigned to a variable, it loses its original context. This means that when greetFunction is called, the this keyword inside the function refers to the global object, which doesn't have a name property. Therefore, the output will be Hello, my name is undefined. + +To preserve the original context of the greet function, you can use bind to create a new function with a specific this value: +