Javascript, preserving this reference when passing function argument

2024/2/26 22:54:52

I'm inside a function of an object and I need to call an external function and pass a reference to a function as argument. This last function argument uses the keyword this several times so I need to be scoped into my object. I solved this by doing:

   MyObj.prototype.internalFunc= function(data){this.doSomethingWithReturnedData(data);};MyObj.prototype.doSomething= function(){var $this = this;externalFunction(this.someVar, function(data){ $this.internalFunc(data); });};var objInst = new MyObj();objInst.doSomething();

I want to know if there is away to avoid this messy var $this = this thing.

I also thoung of:

   //... (same as before)MyObj.prototype.doSomething= function(){var $this = this;externalFunction(this.someVar, this.internalFunc, this);};//... (same as before)


   function externalFunction(arg1, cbfunc, thisref){//bla bla, blablaData);};

but I also find it messy.

I think there is a better way of doing it and I'm not seeing it! Thanks in advance!


There is one other option available to you, if you're on a recent enough browser and that is to use Function.bind.

This allows you to create a function that has been bound to a specific scope. Put another way, it allows you to define what this will be, inside that function. Thus, you could do it this way.

MyObj.prototype.doSomething= function(){externalFunction(this.someVar, this.internalFunc.bind(this, data));

Follow the link above and scroll to the bottom to see information about browser support.


Actually, there's one other option, which is to use one of the many libraries and frameworks that are out there. Any one worth its salt will have a bind, hitch, proxy or otherwise available to you. However, all these are doing are wrapping up the native JS approaches, but they often provide useful additions that make this technique even more valuable.

Related Q&A

split string into array of n words per index

I have a string that Id like to split in an array that has (for example) 3 words per index. What Id also like it to do is if it encounters a new line character in that string that it will "skip&qu…

Prevent SQL injection in WebSQL database? (How to handle quotes in data?)

Im currently importing an xml export of a mysql database into a websql database for use in an online mobile experience.Everything works fine and dandy until there are double quotes in whatever string I…

Node.js to MongoDB: find by Date

Problem with find Date from Node to MongoDB:Its been said MongoDB might not be storing a Date object, but a string, but Im not sure how to check, or how to fix that.In my turnys.js file:exports.findNee…

google maps circle to polyline coordinate array

how to get array of polyline coordinates from google.maps.Circles objectthere is no api doc entry about that

Getting range numbers using recursion in JavaScript

I am trying to get the range of numbers using recursion. Can someone explain to me why it isnt working?function range(x,y){var results = [];if(x === y){return results;}return results.push(range(x + 1…

Recursive using expand() and concatMap() in Angular 7

I have following API list below: 1. { id: 12previous: nullnext: ... }2. https://www.som…

sorting string function by custom alphabet javascript

Trying to sort an array of strings based on a custom alphabet. Probably some unnecessary code in there, but that was a couple different iterations mixed into one.I am doing a base sort of the first let…

How to make the Selected Option the width of the current Selected Options text?

I am trying to make the Select Option to have the width of the current Selected Option.My code is the standard HTML for a Select Option dropdown:<select name="search_options"><option…

How to remove single object from the sessionStorage (AngularJs)

I add list to sessionStorage like:var item = new cartItem(,, product.price, qty); orderItem.push(item); sessionStorage.setItem(addedProductsList, JSON.stringify(orderItem)); var …

Quick regexp to get path

I need to extract the full path to a file using -> -> /mypath/anyone?