𝐖𝐡𝐚𝐭 𝐰𝐢𝐥𝐥 𝐛𝐞 𝐥𝐨𝐠𝐠𝐞𝐝 𝐭𝐨 𝐭𝐡𝐞 𝐜𝐨𝐧𝐬𝐨𝐥𝐞?
𝐖𝐡𝐚𝐭 𝐰𝐢𝐥𝐥 𝐛𝐞 𝐥𝐨𝐠𝐠𝐞𝐝 𝐭𝐨 𝐭𝐡𝐞 𝐜𝐨𝐧𝐬𝐨𝐥𝐞?
First, we have an object named “income” with three properties:
1. “𝐬𝐤𝐢𝐥𝐥𝐬”, which is set to 108.
2. “𝐦𝐨𝐧𝐭𝐡𝐥𝐲”, which is a method that calculates the monthly income based on the “𝐬𝐤𝐢𝐥𝐥𝐬” value.
3. “𝐲𝐞𝐚𝐫𝐥𝐲”, which is an arrow function meant to calculate the yearly income.
𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧 𝐨𝐟 “𝐦𝐨𝐧𝐭𝐡𝐥𝐲()” 𝐦𝐞𝐭𝐡𝐨𝐝:
1. “𝐦𝐨𝐧𝐭𝐡𝐥𝐲()” is a regular function. When you call “𝐢𝐧𝐜𝐨𝐦𝐞.𝐦𝐨𝐧𝐭𝐡𝐥𝐲()”, this refers to the “𝐢𝐧𝐜𝐨𝐦𝐞” object.
2. “𝐭𝐡𝐢𝐬.𝐬𝐤𝐢𝐥𝐥𝐬” inside the “𝐦𝐨𝐧𝐭𝐡𝐥𝐲()” method correctly refers to “𝐢𝐧𝐜𝐨𝐦𝐞.𝐬𝐤𝐢𝐥𝐥𝐬”, which is 108.
3. So, “𝐭𝐡𝐢𝐬.𝐬𝐤𝐢𝐥𝐥𝐬 * 𝟏𝟎𝟖” becomes “𝟏𝟎𝟖 * 𝟏𝟎𝟖”, which equals 11664.
4. Therefore, “𝐢𝐧𝐜𝐨𝐦𝐞.𝐦𝐨𝐧𝐭𝐡𝐥𝐲()” returns 11664.
𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧 𝐨𝐟 “𝐲𝐞𝐚𝐫𝐥𝐲” 𝐚𝐫𝐫𝐨𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧:
1. “𝐲𝐞𝐚𝐫𝐥𝐲” is defined as an arrow function.
2. Arrow functions do not have their own “𝐭𝐡𝐢𝐬” context; they inherit “𝐭𝐡𝐢𝐬” from the surrounding (lexical) context at the time they are defined.
3. In this case, “𝐭𝐡𝐢𝐬” in “yearly” refers to the global object (“𝐰𝐢𝐧𝐝𝐨𝐰” in browsers, “𝐠𝐥𝐨𝐛𝐚𝐥” in Node.js), not the “𝐢𝐧𝐜𝐨𝐦𝐞” object.
4. Since there is no “𝐬𝐤𝐢𝐥𝐥𝐬” property on the global object, “𝐭𝐡𝐢𝐬.𝐬𝐤𝐢𝐥𝐥𝐬” is “𝐮𝐧𝐝𝐞𝐟𝐢𝐧𝐞𝐝”.
5. As a result, “𝟖𝟖𝟖 * 𝐭𝐡𝐢𝐬.𝐬𝐤𝐢𝐥𝐥𝐬” becomes “𝟖𝟖𝟖 * 𝐮𝐧𝐝𝐞𝐟𝐢𝐧𝐞𝐝”, which is “𝐍𝐚𝐍” (Not a Number).
6. Therefore, “𝐢𝐧𝐜𝐨𝐦𝐞.𝐲𝐞𝐚𝐫𝐥𝐲()” returns “𝐍𝐚𝐍”.
𝐓𝐨 𝐬𝐮𝐦𝐦𝐚𝐫𝐢𝐳𝐞:
1. “𝐢𝐧𝐜𝐨𝐦𝐞.𝐦𝐨𝐧𝐭𝐡𝐥𝐲()” works as expected and returns 11664 because “𝐭𝐡𝐢𝐬” correctly refers to the “𝐢𝐧𝐜𝐨𝐦𝐞” object.
2. “𝐢𝐧𝐜𝐨𝐦𝐞.𝐲𝐞𝐚𝐫𝐥𝐲()” returns “𝐍𝐚𝐍” because “𝐭𝐡𝐢𝐬” inside the arrow function does not refer to the “𝐢𝐧𝐜𝐨𝐦𝐞” object, leading to “𝐭𝐡𝐢𝐬.𝐬𝐤𝐢𝐥𝐥𝐬” being “𝐮𝐧𝐝𝐞𝐟𝐢𝐧𝐞𝐝”.
𝐅𝐨𝐥𝐥𝐨𝐰 𝐭𝐡𝐢𝐬 𝐩𝐚𝐠𝐞 𝐟𝐨𝐫 𝐦𝐨𝐫𝐞 𝐜𝐨𝐧𝐭𝐞𝐧𝐭 𝐥𝐢𝐤𝐞 𝐭𝐡𝐢𝐬.
No comments:
Post a Comment