M M
M M

Reputation: 2249

replacing a function passed by reference in javascript

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

Answers (2)

Kevin B
Kevin B

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

Ruan Mendes
Ruan Mendes

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

Related Questions