Establishing the prototype of a function constructor (demonstrated)

I've been grappling with an example from a course titled "JavaScript: Understanding the Weird Parts". In this example, there's a line of code

Greeter.init.prototype = Greeter.prototype;
, which sets Greeter.prototype as the prototype for all objects created using the Greeter.init function constructor. This allows us to define methods in Greeter.prototype.

However, I'm puzzled as to why we can't just set the methods directly in Greeter.init.prototype. It seems like the line

Greeter.init.prototype = Greeter.prototype;
is unnecessary. What advantage does the original approach offer?

Original code:

(function(global, $) {
    
  var Greetr = function(firstName, lastName, language) {
      return new Greetr.init(firstName, lastName, language);   
  }

  Greetr.prototype = {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  };

  Greetr.init = function(firstName, lastName, language) {      
    var self = this;
    self.firstName = firstName || '';
    self.lastName = lastName || '';
    self.language = language || 'en';       
  }

  Greetr.init.prototype = Greetr.prototype;

  global.Greetr = global.G$ = Greetr;
    
}(window, jQuery));


var g = G$('John', 'Doe');
console.log(g);
console.log(g.fullName());
<html>
    <head>
        
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </body>
</html>

Simplified code:

(function(global, $) {
    
  var Greetr = function(firstName, lastName, language) {
      return new Greetr.init(firstName, lastName, language);   
  }

  Greetr.init = function(firstName, lastName, language) {      
    var self = this;
    self.firstName = firstName || '';
    self.lastName = lastName || '';
    self.language = language || 'en';       
  }

  Greetr.init.prototype = {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  };

  global.Greetr = global.G$ = Greetr;
    
}(window, jQuery));


var g = G$('John', 'Doe');
console.log(g);
console.log(g.fullName());
<html>
    <head>
        
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </body>
</html>

Answer №1

When the Greetr constructor invokes the Greetr.init constructor and explicitly returns an object to override its return value, there is essentially no distinction between them.

Both code snippets generate the same object structure and function equivalently, with a minor discrepancy: the second snippet maintains Greetr.prototype in its original state.

It is highly probable that in the initial code, Greetr.prototype and Greetr.init.prototype were set to the same object. This approach allows for easy access and extension without necessitating the use of .init, which enhances semantic clarity – indicating an intention to modify the prototype of objects created by Greetr, whose usual prototype is Greetr.prototype. Moreover, in the first snippet, instances generated by Greetr and Greetr.init will be identified as instances of Greetr when evaluated using instanceof.

(function(global, $) {
    
  var Greetr = function(firstName, lastName, language) {
      return new Greetr.init(firstName, lastName, language);   
  }

  Greetr.prototype = {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  };

  Greetr.init = function(firstName, lastName, language) {      
    var self = this;
    self.firstName = firstName || '';
    self.lastName = lastName || '';
    self.language = language || 'en';       
  }

  Greetr.init.prototype = Greetr.prototype;

  global.Greetr = global.G$ = Greetr;
    
}(window, jQuery));


var g = G$('John', 'Doe');
console.log(g instanceof G$);
<html>
    <head>
        
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </body>
</html>

(function(global, $) {
    
  var Greetr = function(firstName, lastName, language) {
      return new Greetr.init(firstName, lastName, language);   
  }

  Greetr.init = function(firstName, lastName, language) {      
    var self = this;
    self.firstName = firstName || '';
    self.lastName = lastName || '';
    self.language = language || 'en';       
  }

  Greetr.init.prototype = {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  };

  global.Greetr = global.G$ = Greetr;
    
}(window, jQuery));


var g = G$('John', 'Doe');
console.log(g instanceof G$);
<html>
    <head>
        
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Node.js error creating directory (module mkdir not found)

I am looking to create a simple script using node.js that will generate a standard folder named "Project" for me. The next step is to add three files within the folder: index.html, app-js, and styles.css. const mkdir = require('mkdir'); //const f ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

When setting the form action attribute in jQuery, the parameter being passed may be null

My goal is to redirect my form action to another page with a URL parameter. Here's the code I'm using: ui.setFormActionToTargetPage = function () { $('form').get(0).setAttribute('action', 'myTargetPage.html?id=' ...

Preserve selected value in dropdown menu post form submission

Is there a way to have the selected option displayed on a drop-down list after form submission instead of always showing the first option? <form id="myform" > <label for="selectoption">Departments</label> ...

Unexpected token N error was thrown while using the Jquery .ajax() function

While working on a form submission feature using JQuery .ajax() to save data into a MySQL database, I encountered an error message that says "SyntaxError: Unexpected token N". Can someone please explain what this means and provide guidance on how to fix it ...

Guide on obtaining the file path of an uploaded file through the use of HTML, JavaScript, and PHP

After successfully uploading an image from my drive, I am encountering an issue where I am unable to locate the folder path of that image For example: C:\Images\Logo\Image.png $('#pngfile').change(function (e) { var tmppath = URL ...

How to retrieve the current element in AngularJS version 1.x

I have done extensive research on how to get the current element in jQuery using $(this). However, I have not been able to find a similar method in AngularJS 1.x. Here is what I have tried: angular.element(this), but it does not work as expected. Below is ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

What are the implications of using eval() to interpret function parameters?

I've recently utilized Hopscotch to create a interactive tour on my Website. To implement this, you need to create a JavaScript object as a parameter to trigger the startTour() function which will kick off the tour. For instance, in this case, the tou ...

Is it possible for me to use any text as a JSON key?

Is it acceptable to use any utf-8 string as a property name in JSON? For example, is the following valid: var personData = { 'Matti Möttönen': { "FirstName": "Matti", "LastName": "Möttöne ...

Banish document in Brunch regex pattern

How can I exclude the file mapdata.coffee located in the view folder from the joinTo configuration in Brunch? This is what I attempted: 'javascripts/app.js':/^app(\/|\\)(?!(tests|store-test|views\/mapdata.coffee))/ What am ...

Is invalid HTML causing issues with Backbone.js templating in Phonegap?

Summary: When my template file contains valid HTML code, it does not display in Phonegap. The structure of my index.html file is as follows: <body onload="onBodyLoad()"> <div data-role="page"> <a href="#login" id="clickme">C ...

Having trouble accessing array value in Reactjs - returning undefined

I am currently in the process of comparing values from 2 different arrays that contain state data. However, I am encountering an issue where the value of otherItems[i] is returning as undefined. To provide some context, the array Items consists of Objects ...

Is there a way to transfer the content from a textarea to a DIV in a specific format?

I have a text area and button set up to send the text area value (content) into <div id="rs"></div>, with each separate line of the textarea box being appended to the div as a new element when the Enter button or Line breaks occur. F ...

How do I prevent a specific word from being removed in a contenteditable div using JavaScript?

Attempting to create a terminal-like experience in JS, I am looking to generate the word 'current source, current location' (e.g., admin@ubuntuTLS~$: ~/Desktop) at the beginning which cannot be removed. Also, I want to prevent the caret from bein ...

Avoiding external variable reference through Jest.mock

For snapshot testing, I need to create a simple dummy mock of 1 react component. When attempting to use React.Component within the mock function, an error is thrown: The second argument of jest.mock() cannot reference external variables. However, usin ...

Using yajrabox to create a loop in Laravel for Datatables through an ajax call

function generateDataTableWithDates(tgl = null, tglA = null, tglB = null, departemenId = null, group = true){ setColumn(group); var tgl = {}; for (var i=1; i < 32; i++) { tgl[i] = i; }; $('.tableCustom3 ...

`What is the best way to access value during an onChange event?`

I'm currently utilizing react-input-calendar for my project. My goal is to extract the date value from the onChange event and then transfer it to a new page. Can someone provide guidance on how to achieve this? Here is the code snippet: constructor( ...

Starting up a React application with the constructor

I am trying to understand the logic behind having to instantiate a new AppInitializer in order to run it. Why is it necessary to use new AppInitializer().run(); instead of just AppInitializer.run();? class AppInitializer { run() { render( &l ...

Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked. However, we are facing issues where clicking on the order button doesn't register in the applicat ...