Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: unexpected typeof result

I have an array iterator function:

function applyCall(arr, fn) {
  fn.call(arr[0], 0, arr[0]);
}

and some code

var arr1 = ['blah'];
applyCall(arr1, function (i, val) {
  alert(typeof this); // object    WHY??
  alert(typeof val); // string
  alert(typeof(this === val)) // alerts false, expecting true
});

Why is typeof this within the inline function object instead of string?

jsfiddle here

like image 680
Polshgiant Avatar asked Feb 20 '13 03:02

Polshgiant


People also ask

Why typeof null is object in JavaScript?

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.

What does typeof return?

The typeof operator returns a string indicating the type of the operand's value.

What is typeof operator in JavaScript?

Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator.

How do you find the type of error?

To check if a variable is of type Error , use the instanceof operator - err instanceof Error . The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.


1 Answers

When a method is called in JavaScript, it internally sets this to the calling object: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

...and primitive values will be boxed.

By "boxed," they mean that the primitive is wrapped in an Object. Note that this only applies to the first argument to apply/call. The other arguments become function parameters that are not "boxed."

like image 101
Explosion Pills Avatar answered Nov 09 '22 14:11

Explosion Pills