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?
“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.
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).
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).
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 thethis
value is not coerced to an object. A this value ofnull
orundefined
is not converted to the global object and primitive values are not converted to wrapper objects. Thethis
value passed via a function call (including calls made usingFunction.prototype.apply
andFunction.prototype.call
) do not coerce the passed this value to an object (9.2.1.2, 19.2.3.1, 19.2.3.3).
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