Im struggling with the general mechanics of the “this” keyword… or should i say… there are only verryy isolated incidents where im actually SURE of what “this” is going to do… mdn just keeps leaving me with more questions than answers… any form of help would be greatly appreciated
** I understand i havent really asked a question here
Well in that particular case it’s attaching a function to the Array object that mimics the built-in filter function, not the built-in map function. That’s not super important, it was just an example, the person was also asking what this is.
Everything you can call functions on is an object in JS. Even at the top level, you’re executing functions in the context of a global object (called window in browsers).
this is whatever is to the left of the dot when a function is called
user.fullname(): the object user is to the left of the dot, user.fname is “Dan”, user.sname is “Couper”,
If you define a class, the class is created using a JS keyword called new and a function called a constructor: new creates an object, the constructor executes in the context of that object.
No. this solves the problem of “I have an object. It has a function attached to it. How do I refer to that actual exact object the function lives in from inside that function”
yea ik which i appreciated… but then my assignment turned into a tie in which now i still need help with cuz…
console.log(callback) and console.log(callback.this) did nothing…
didnt even show [func] in the console so im still stuck as far as how to grab ahold of whats inside “callback”
i set both console calls in the function scope… where callback exists also
Your assignment is to attach a function to the Array.prototype object. The function takes one argument, called callback, which is going to be a callback function.
this refers to the object your map function is attached to, which is an array.
Your function still takes an argument, that argument is still going to be some function
callback.this isn’t a thing. this isn’t a property on an object, it’s a placeholder for whatever the context is
Array.prototype.myMap = function(callback) {
const newArray = [];
// Only change code below this line
let callback =function(){
for(let i = 0 ; i < this.length ; i += 1){
let item = this[i];
newArray.push(item)
}
}
// Only change code above this line
return newArray;
};