I am learning JavaScript and I am trying to replicate some of the built-in methods like .push() .indexOf() etc..
So far so good and it is helping me a lot to learn the core of JavaScript.
But I came across .bind() and I can´t figure out a way of knowing the function that is calling the .bind() and tell my new .bind2() method to use it with the new THIS from our Object.
This is what I am trying:
const human = {
firstName:"Humano",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
const member = {
firstName:"Member",
lastName: "Nilsen",
};
Function.prototype.bind2 = function(obj) {
if (typeof obj !== "object" ) {throw `${obj} is not an Object, I will work hard to return undefined later on`};
return function(){
return obj;
}
};
let testBind2 = human.fullName.bind2(member);
console.log(testBind2()); // {firstName: 'Member', lastName: 'Nilsen'}
So all I could do is to return the THIS from the Object passed as an argument but I have no idea how I can grab inside the .bind2() the fullName method (or any method that we want to bind) from the object that is actually calling the method .bind2().
Once we could grab the fullName we can pass it to bind2() and tell it to use THIS from our object.
This is only for the sake of learning and it would be amazing if someone could tell me if it is possible and how.
Thank you
var that=this;andreturn that.apply(this, arguments)