I am trying to implement 2 questions.
// Question 1: Given a greet() function modify it to update its context with an object
// having firstName and lastName properties.
function greet(name) {
console.log("lalalalaHi " + name + " " + this + " is the original context of the function");
}
greet("Ron");
var obj = {
firstName: "Alex",
lastName: "Riley"
}
greet.call(obj, "Ron");
// Question 2: Given a greet() function modify it to update its context with an object
// having firstName and lastName properties
// and allow it to accept multiple arguments in an array
function greet(name, lastName) {
console.log("Hi " + name, lastName + ", I am " + this.firstName, this.lastName);
}
myDetails = { "firstName": "Harry", "lastName": "Potter" }
greet.apply(myDetails, ["Ron", "Weasley"]); //Passing object myDetails for this keyword
myDetails = { "firstName": "James", "lastName": "Potter" }
greet.apply(myDetails, ["Ron", "Weasley"]); //Passing object myDetails for this keyword
When I am executing 1st question alone, I am getting output as,
lalalalaHi Ron [object global] is the original context of the function
lalalalaHi Ron [object Object] is the original context of the function
But when I am executing both together, my output for 1st ques is also getting changed
Hi Ron undefined, I am undefined undefined
Hi Ron undefined, I am Alex Riley
Please help me understand, what is happening here.
I ran the questions separately and together in both the cases I am getting different output.
How is this working…