Posted on • Originally published atsargalias.com
This binding in JavaScript – 4. New binding
This post (This binding in JavaScript – 4. New binding) was originally published onSargalias.
In this series we talk aboutthis binding in JavaScript.
This is a very important topic. It's also something that even experienced developers frequently get wrong and / or have to think about.
Basically in JavaScript there are 4 modes forthis binding. Make that 5 if we include arrow functions.
In order of lowest priority to highest priority, here they are:
- Default binding
- Implicit binding
- Explicit binding
- New binding
- Arrow functions
- Gotchas and final notes
In this post we'll talk about new binding.
How new binding works
new is a special keyword in JavaScript.
It does a lot of things, but we'll only talk in detail about how it relates to binding.
To start off, note thatnew has even higher precedence than even hard binding. Another way of thinking about it is that it ignores the normal binding rules and does its own thing.
You can usenew when calling functions like so:new foo().
new does 4 things:
- It creates a new empty object.
- It makes
thisbe the new object. - It makes
foo.prototypebe the prototype of the object. - It implicitly returns
thisif nothing else is returned from the function.
For now ignore points 3 and 4 until a different blog post. Let's focus on points 1 and 2, the binding.
To recap, when you call a function withnew before it, you create a brand new empty object which is assigned tothis inside the function.
For example:
functionfoo(){console.log(this);}newfoo();// outputs an empty objectAs mentioned,new has higher precedence than even hard binding.
constobjForBind={name:'objForBind'};functionfoo(){console.log(this);}constboundFoo=foo.bind(objForBind);// hard bind foo to objForBindnewboundFoo();// logs a new empty object to the console, not objForBindExplanation:new has higher precedence than explicit and implicit binding. It ignores them, creates a new object, and binds it tothis.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse



