0

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?

juffel
  • 1,045
  • 15
  • 21
  • 2
    This reads like an [XY Problem](http://xyproblem.info/). What do you hope to achieve by doing this? – Quentin Sep 13 '16 at 10:31
  • 1
    if javascript behaviour is to convert primitives to objects, then I can't see how you can avoid it, short of writing your own javascript engine ... however, that statement implies this behaviour is in strict mode only – Jaromanda X Sep 13 '16 at 10:32
  • Why do you care if `this` is a primitive? If that's what you want, why not pass it as a parameter? –  Sep 13 '16 at 10:34

2 Answers2

1

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)
Nikhilesh Shivarathri
  • 1,640
  • 10
  • 16
1

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.

Community
  • 1
  • 1
kingshuk basak
  • 423
  • 2
  • 8