Why is the JavaScript constructor not being executed?

I am currently working on implementing a JavaScript inheritance example that I came across, but I am encountering issues with the child object not constructing as expected. When attempting to create the jill instance in the code snippet below, it does not return a Jill object, leading to difficulties in calling methods from either the child or parent.

var Person = function() {
  this.name = "unnamed";
}
Person.prototype.sayName = function() {
  console.log("My name is " + this.name);
}
var Jill = function() {
  var jill = function() {
    Person.call(this);
    this.name = "Jill";
  };
  jill.prototype = Object.create(Person.prototype);
  jill.prototype.constructor = jill;
  jill.prototype.expressJoy = function() {
    console.log("Huray!");
  };
  return jill;
}
var jill = new Jill();
console.log(jill instanceof Jill); // false
jill.expressJoy(); // error, is not a function
jill.sayName(); // error, seen if comment out previous line

Answer №1

If we take a look at your situation, the variable var Jill is functioning more like a regular function rather than a constructor.
Here's how you can modify your code to rectify this:

var Jill = (function() {
    function Jill() {
        Person.call(this);
        this.name = "Jill";
    };
    Jill.prototype = Object.create(Person.prototype);
    Jill.prototype.constructor = Jill;
    Jill.prototype.expressJoy = function() {
        console.log("Huray!");
    };
    return Jill;
})();

var jill = new Jill();
console.log(jill);   // Jill {name: "Jill"}
console.log(jill instanceof Jill); // true
jill.expressJoy(); // Huray!
jill.sayName();    // My name is Jill

Now, after these changes, Jill will work as a proper constructor and create objects as expected. (By the way, it's good practice for constructor names to begin with an uppercase letter).

Answer №2

You have made a mistake in initializing the object,

var jack = Jack();
var obj = new jack();

The function Jack is actually returning a function pointer rather than an actual object. In order to fix this, you will need to create an object based on the returned function pointer.

Answer №3

This code has been revised and includes a detailed explanation:

Check out the JSBin Example

// The following is the Person class which serves as a base for all "people"

var Person = function() {
  this.name = "unnamed";
};

// Adding the sayName function to the prototype of Person
Person.prototype.sayName = function() {
  console.log("My name is " + this.name);
};

// Creating the 'Jill' constructor
var Jill = function() {
  Person.call(this); // Linking Person to Jill
  this.name = 'jill';
};

// Updating the prototype delegation for Jill
Jill.prototype = Object.create(Person.prototype);

// Resetting Jill's constructor to point back to Jill
Jill.prototype.constructor = Jill;

// Adding functions to Jill's prototype 
Jill.prototype.expressJoy = function() {
    console.log("Huray!");
  };

// Instantiating a new object named 'obj' from Jill
var obj = new Jill();
console.log(obj instanceof Jill); // Outputs true
obj.expressJoy(); // Outputs "Huray!"
obj.sayName(); // Outputs "My name is jill"

It's important to note that this code combines prototypal and pseudoclassical instantiation patterns - Person follows the latter while Jill utilizes the former.

For more information on JavaScript instantiation patterns, refer to this informative blog post by Ryan Atkinson:

Read the Blog Post

https://i.sstatic.net/jUzkW.jpg

Answer №4

Follow these steps to implement your code:

1) return new jill(); within the inner function, then

2) var jill = Jill(); to invoke the function that generates the new instance.

DEMO

This approach is more straightforward.

function Person() {
  this.name = "unnamed";
}

Person.prototype.sayName = function() {
  console.log("My name is " + this.name);
}

function Jill() {
  Person.call(this);
  this.name = "Jill";
}
Jill.prototype = Object.create(Person.prototype);
Jill.prototype.constructor = Jill;
Jill.prototype.expressJoy = function() {
  console.log("Huray!");
};

var jill = new Jill();

DEMO

Answer №5

Here's a functioning code snippet:

function Being() {
  this.type = "unknown";
};
Being.prototype.identifyType = function() {
  console.log("I am a " + this.type);
};

function Sarah() {
    Sarah.prototype.__proto__ = Being.prototype;

    this.type = "human";

    Sarah.prototype.expressExcitement= function() {
        console.log("Yay!");
    };

    return Sarah;
};

var sarah = new Sarah();
console.log(sarah instanceof Sarah); // True
sarah.expressExcitement(); // Yay!
sarah.identifyType(); // I am a human

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

Unexpected output in JavaScript when using regular expressions

I am attempting to utilize node for some regex operations on a css file. This is my javascript code: var fs = require ('fs'); fs.readFile('test.css','utf8',function(error,css){ if(error){ console.log("I'm sorry, so ...

Having trouble installing NPM with jQuery? Getting errors about 'Define is undefined'?

After installing jQuery using NPM, I am attempting to integrate it into an existing webpage. Upon checking the console, I am encountering the following error: https://i.sstatic.net/bNIni.png In my code, the structure is as follows: <!DOCTYPE html&g ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

Error message indicating an issue with defaultProps on a React FunctionComponent in Typescript

Looking at this React Functional Component: import React, { memo } from 'react'; interface Options { buttonType?: JSX.IntrinsicElements['button']['type']; text: string; }; const defaultSettings = { buttonType: 'b ...

Select the anchor attribute value of tabs using jQuery

After upgrading from jQuery 1.7 to 1.9, we encountered an issue with one of our functions no longer working. Our previous code used to retrieve the value of the anchor tag in the currently selected tab. select:function(event,ui) { var messageId=$(ui ...

transferring data from JavaScript to AJAX in MVC4

I am facing an issue where I need to select a value from a grid and pass it to ajax, but I keep getting an error saying "Id undefined". Can anyone help me find a solution for this problem? The goal is to delete records that are presented in the grid. Upon ...

Ways to embed a series of images within a stationary container

I have a fixed lateral div (like a menu bar) and I am exploring options for displaying images in a table-like format within the div. The challenge is that these images are dynamically generated. Specifically, I need to place 10 images in the div. While I ...

At times, Chrome fails to load CSS files when requested

Whenever I visit this ASPX page, the stylesheets sometimes fail to load. There is no request made and even checking the network log in Chrome's debugger confirms that it didn't request or load from cache. Interestingly, all other resources such a ...

Methods for adding a new object to an array in Angular: Explained

How can I insert a new object in Angular? Here is the current data: data = [ { title: 'Book1' }, { title: 'Book2' }, { title: 'Book3' }, { title: 'Book4' } ] I would like to update the obje ...

My Contentful code is not functioning properly in NodeJS

I am encountering an issue with the code below, which is meant to display content of type "course." When I try to access http://localhost:3000/api/courses, the browser keeps loading indefinitely without any error messages in the console. Interestingly, t ...

What is the reason behind appending a timestamp to the URL of a JavaScript resource?

$script.ready('jui',function() { $script('<?php base_path(); ?>js/partnerScripts.js?ts=1315442861','partners'); }); Can anyone explain why there is a fixed ts=timestamp at the end of the partnerScripts.js file name? I ...

A guide on transforming a 3D mesh into a 2D shape using Three.js

I am working on converting a 3D mesh into a 2D shape. My goal is to achieve a result similar to the one shown in this image. The image displays a given mesh and its silhouettes from various viewpoints. I aim to replicate this process for any given mesh us ...

Doing calculations in a GridView using JavaScript

Hello, I am wondering how I can implement the following JavaScript on an ASP.NET GridView since it will be rendered as a table in the browser. You can check out a demo on an HTML table here: jsfiddle Here is the JavaScript code: In this code, I calculat ...

The installation of @grpc/grpc-js does not include all necessary dependencies

Recently, I incorporated @grpc/grpc-js into my project using the command npm i @grpc/grpc-js. Surprisingly, there are no compile time errors when I attempt to use it. However, at runtime, a series of errors arise: ./node_modules/.pnpm/@<a href="/cdn-cgi ...

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...

The ThreeJS model loader encountered an error while attempting to load within a class method

Currently, I am in the process of constructing a ThreeJS scene and coding it as a class: export class RenderCanvas { #scene; // THREE.Scene() // Other properties and methods loadGeometries() { /* #scene is initialized before loadGeom ...

Is it possible to load a JavaScript file from a different domain using a bookmarklet?

I'm a newcomer to bookmarklets and I am experimenting with loading a JavaScript file from my own server/domain using the following bookmarklet/javascript code: javascript:(function(){s=document.createElement('script'); s.type=' ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...

Not including absent keys in JSON comparison

I am seeking a solution for comparing two JSON documents in Jest unit testing. The challenge is that they should be considered equal, except for the fact that the second document contains an additional key: _id. Here is an example: doc1.json { userna ...

What could be causing Angular 8 form to be submitted multiple times?

I am a beginner when it comes to Angular. I have created a form with the following structure: <h2>Login</h2> <form [formGroup]="loginForm" (ngSubmit)="onSubmit()"> <div class="form-group"> & ...