Martin Cup
Martin Cup

Reputation: 2582

javascript: get value of `this` when calling function with apply

When I call

var fun = function(input) {
  console.log(!!this, this, typeof(this), Object.keys(this), !this.toString(), this.constructor.name); 
  // logs: true [Boolean: false] object [] false Boolean
  if(!this) return input;
  return this;
}
var someVar = false;
var result = fun.apply(someVar, ["TEST"]);

I would expect the result to be "TEST", but the result is a strange object printed in the console as [Boolean: false].

The question is, what is the most elegant way to check inside the function if this (passed in as someVar) has some kind of falsy value so that "TEST" would be returned in this example?

The code is running in node js.

Upvotes: 0

Views: 24

Answers (1)

Bergi
Bergi

Reputation: 664548

You need to use strict mode in your function so that its this value does not get coerced to an object:

var fun = function(input) {
  "use strict";
  console.log(!!this, this, typeof this);
  if (!this) return input;
  return this;
}
var someVar = false;
var result = fun.call(someVar, "TEST");

Upvotes: 2

Related Questions