Reputation: 2249
My understanding is in javascript a function is passed by reference... and in this case I am trying to replace one function with another. It is not working. I am sure I am missing something simple. But what?
var spit = {
spittle: function (x) {
console.log('i spittle at ' + x);
}
}
replaceFunc = {
replace: function (func) {
func = console.log;
}
}
replaceFunc.replace(spit.spittle);
spit.spittle('joe'); /// should be just 'joe' instead the spittle func is not replaced and it outputs 'i spittle at joe'
Upvotes: 1
Views: 131
Reputation: 95066
replaceFunc.replace(spit.spittle);
passes the function stored in spit.spittle
into the function stored in replaceFunc.replace
, therefore, once you're inside of the replace function, it can't get back to the spittle
property of spit
other than by directly referencing it as spit.spittle
.
One workaround would be to pass both the object and the name of the property you want to replace into the function.
var spit = {
spittle: function (x) {
console.log('i spittle at ' + x);
}
}
replaceFunc = {
replace: function (obj, key) {
obj[key] = console.log.bind(console);
}
}
replaceFunc.replace(spit, 'spittle');
spit.spittle('joe'); /// should be just 'joe'
Upvotes: 1
Reputation: 92314
There is no pass by reference in JavaScript. An option is to pass the entire spit
object and modify it.
var spit = {
spittle: function (x) {
console.log('i spittle at ' + x);
}
}
var replaceFunc = {
replaceSpittle: function (funcContainer) {
funcContainer.spittle = function() {
console.log.apply(console, arguments);
}
}
}
replaceFunc.replaceSpittle(spit);
spit.spittle('joe');
Upvotes: 2