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
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.
The typeof operator returns a string indicating the type of the operand's value.
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.
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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With