Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (function(){return this}).bind('abc')()==='abc' equals to false?

Tags:

javascript

Suppose I have a function like that:

var f1=function(){
   return this;
};
console.log(f1.bind('abc')()==='abc');

as I know, f1.bind('abc') should create a new function that returns 'abc', so I guess it should have output same as

console.log('abc'==='abc')

which is true, but now the output is false, what's wrong with my guess?

like image 239
ocomfd Avatar asked Mar 02 '18 06:03

ocomfd


People also ask

What does the this function do?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.

What type of function doesn't have its own this keyword instead it always uses this to refer to its containing environment?

Arrow functions don't have their own this […] binding. Instead, [this identifier is] resolved in the lexical scope like any other variable. That means that inside an arrow function, this [refers] to the [value of this ] in the environment the arrow function is defined in (i.e. “outside” the arrow function).

How does the this keyword work?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).


1 Answers

In non-strict mode, the primitive values are wrapped in Object. So, 'abc' becomes new Object('abc').

In strict mode, this does not happen.

'use strict';

var f1 = function() {
  return this;
};
console.log(f1.bind('abc')() === 'abc');

Quoting from ES6 Specifications for strict mode

If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object (9.2.1.2, 19.2.3.1, 19.2.3.3).

like image 136
Tushar Avatar answered Nov 14 '22 21:11

Tushar