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?
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.