Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding function to null

Tags:

javascript

function f() {
  return this.x
}
f = f.bind(null)
f() // undefined
x = 1
f() // 1

I cannot find any page where it says that binding to null or undefined has no effect. Everywhere it is written that this becomes a link to the first argument of bind, exceptions are not mentioned. Can somebody provide a link to somewhere describing such behaviour?

like image 640
Serge Seredenko Avatar asked Apr 13 '15 05:04

Serge Seredenko


People also ask

What is bind null?

bind(null, playsound) , it creates and returns a new function, always receiving playsound as first argument and using global context (Because null is used as context), just like all regular functions use global context, when you call them without new operator and not using . call() or apply() with specific context.

What does bind () do in JavaScript?

bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What is a binding function?

Summary. The bind() method creates a new function, when invoked, has the this sets to a provided value. The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

How do you bind a function in Windows?

You can explicitly create properties of the global context ( window ): function g() { window. someFunction = function() { console. log("hi!"); }; } g(); someFunction(); // "hi!"


1 Answers

This behavior is different between strict mode and non-strict mode.

In non-strict mode, if you set thisArg to be null or undefined, this will be coerced to the global object (window).

In strict mode, this could be null, you will got an error.

function f() {
  'use strict';
  return this.x
}
f = f.bind(null)
f() // TypeError: Cannot read property 'x' of null
like image 75
xdazz Avatar answered Sep 17 '22 22:09

xdazz