node memcached have a function get
to retrieve memcachd key value for e.g.:
memcached.get( "hello",function( err, result ){
if( err ) console.error( err );
this.r = result;
console.dir( result );
memcached.end();});
The second argument in the function is the callback function
inside the callback function I can log the value of my key easily.
I tried to assign a property r
to memcached
and when I try to log the memcached.r
outside get
function undefined
result occurs.
What's wrong with my code?
Although this
looks like a variable and often behaves like one, it isn't truly a variable and thus does not behave like one in closures. When you've got one function nested inside another, the inner function gets a completely new version of this
which is very unlikely to point to the same thing as the outer function's this
.
Therefore, if you need to refer to an outer function's this
inside an inner function, you have to first copy it into a true variable (most people like to call it self
but some prefer that
) and then refer to that variable in the inner function.
In your case, however, you've already got a real variable, namely memcached
, that you can assign to, so just replace this
with memcached
in your callback. It's a properly-scoped outer variable of the closure created by your callback (as can be seen by the fact that you can use memcached.end()
in it).
[Update to include correctly formatted version of your code mentioned in comment]
memcached.get = function get(key, callback) {
if (Array.isArray(key)) return this.getMulti.apply(this, arguments);
this.command(function getCommand (noreply) {
return { key: key , callback: callback ,
validate: [['key', String], ['callback', Function]] ,
type: 'get' , command: 'get ' + key };
});
};
It looks like you're trying to call several functions asynchronously and expecting to return
a value from them. That simply won't work.