Reputation: 1115
I want to pass an index-variable as this
to a function I call with function.call()
.
var fun = function() {
console.log( this );
}
fun.call( 1 );
// -> Number {[[PrimitiveValue]]: 1}
So obviously the primitive integer 1
is not passed as primitive to the called function.
According to MDN for Function.prototype.call() "[...] primitive values will be converted to objects."
Is there a way to pass it to fun()
as primitive integer?
Upvotes: 0
Views: 245
Reputation: 421
Well what you want is never possible as per the definition of this inside a function. Yes there can be way arounds as given in the other answers for your implementation.
Upvotes: 1
Reputation: 1670
In the above example 1
is passed as an integer
param but internally it is a object of number
type to the fun
function. So in order to access the value of integer
from this
. Use this.valueOf()
. I think this helps you!
var x = 12;
function fun() {
console.log(this.valueOf());
}
fun.call(x)
Upvotes: 1