Skip to main content

Javascript’s "new" Keyword Explained as Simply as Possible

Javascript’s “new” Keyword Explained as Simply as Possible

Normal Function Call

To explain what new does, let’s start with just a normal function, called without new. We want to write a function that will create “person” objects. It’ll give these objects name and age properties based on parameters that it takes in.

function personFn(name, age) {
var personObj = {};
personObj.name = name;
personObj.age = age;

return personObj;
}
var alex = personFn('Alex', 30);
// -> { name: 'Alex', age: 30 }

Simple enough. We create an object, add the properties to it, and return it at the end.

new

Let’s create a function that does the same thing, but we want it to be invoked using new. This function will create the same object as the one above. Common practice is to make functions that are meant to be invoked with new start with a capital letter. These functions are also referred to as constructors.

function PersonConstructor(name, age) {
this.name = name;
this.age = age;
}
var alex = new PersonConstructor('Alex', 30);
// -> { name: 'Alex', age: 30 }

Invoking personFn normally and invoking PersonConstructor with new both result in the same object being created. What’s going on?

The new keyword invokes a function in a special way. It adds some implicit code that we don’t see. Let’s expand the above function to show everything that’s happening. The commented lines are pseudocode representing functionality that is implicitly added by the JS engine when using new.

function PersonConstructor(name, age) {
// this = {};
// this.__proto__ = PersonConstructor.prototype;
// Set up logic such that: if
// there is a return statement
// in the function body that
// returns anything EXCEPT an
// object, array, or function:
// return 'this' (the newly
// constructed object)
// instead of that item at
// the return statement;
this.name = name;
this.age = age;
// return this;
}

Let’s break it down. new:

  1. Creates a new object and binds it to the this keyword.
  2. Sets the object’s internal [[Prototype]] property, __proto__, to be the prototype of the constructing function. This also makes it so the constructor of the new object is prototypically inherited.
  3. Sets up logic such that if a variable of any type other than objectarray, or function is returned in the function body, return this, the newly constructed object, instead of what the function says to return.
  4. At the end of the function, returns this if there is no return statement in the function body.

Let’s show that these statements are valid, one by one.

function Demo() {
console.log(this);
this.value = 5;
return 10;
}
/*1*/ var demo = new Demo(); // -> {}
/*2*/ console.log(demo.__proto__ === Demo.prototype); // -> true
console.log(demo.constructor === Demo); // -> true
/*3*/ console.log(demo); // -> { value: 5 }
function SecondDemo() {
this.val = '2nd demo';
}
/*4*/ console.log(new SecondDemo()); // -> { val: '2nd demo' }

If you aren’t familiar with constructors or prototypes, don’t worry about it too much. You’ll run into them as you continue to learn Javascript. For now, just understand that the new object implicitly returned by the constructor function will be able to inherit properties and methods.

Calling a non-constructor with new

What happens if we invoke a normal function like personFn using new? Nothing special. The same rules apply. in the case of personFn, we see nothing explicitly happening.

var alex = new personFn('Alex', 30);
// -> { name: 'Alex', age: 30 }

Why? Let’s add our implicit code in to personFn.

function personFn(name, age) {
// this = {};
// this.constructor = PersonConstructor;
// this.__proto__ = PersonConstructor.prototype;
// Set up logic such that: if
// there is a return statement
// in the function body that
// returns anything EXCEPT an
// object, array, or function:
// return this (the newly
// constructed object)
// instead of that item at
// the return statement;
var personObj = {}; personObj.name = name;
personObj.age = age;

return personObj;

// return this;
}

The implicit code is still added in:

  • It binds this to a new object and sets its constructor and prototype.
  • It adds logic that will return this instead of a non-object.
  • It adds an implicit return this statement at the end.

This doesn’t affect our code, since we don’t use the this keyword in our code. We also explicitly return an object, personObj, so the returning logic and the return this line have no use. Effectively, using new to invoke our function here has no effect on the output. If we were using this or if we weren’t returning an object, the function would have different effects when invoked with and without new.

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...