invoking a function through prototype

<script>     
  var Nancy = function(){   
       this.name = 'nancy'
  }          
  Nancy.prototype.getNancy = function(){          
       alert(this.name);        
  }            
  Nancy.prototype.getNancy();

  function Bob(){
     this.name = 'bob'
  }      
  Bob.getStaticBob = function(){
     alert(this.name);    
  }

  Bob.prototype.getBob();
  Bob.getStaticBob();

</script>
  1. What causes the return value of undefined when calling the method using prototype?
  2. Why does the static method in Bob class print the output correctly?

Answer №1

In order to invoke the methods from within the constructor, you must instantiate an anonymous instance like so:

(new John).getJohn(); // alternatively new John().getJohn()

Answer №2

The reason you are receiving `undefined` is because the prototype does not have a "name" property. It's important to note that although your call to "getStaticJohn()" may appear to be functioning perfectly, it actually alerts "John" with a capital "J" because it is accessing the "name" property of the function object "John".

When you invoke a method using an expression like `something.functionName`, the value of `this` within the function will always refer to the value of `something`. So, when you make the call:

John.prototype.getJohn();

The value of `this` inside the "getJohn()" function will be `John.prototype`, and not any instance created by the "John()" constructor.

If you include the following code:

John.prototype.name = "John's prototype";

then calling John.prototype.getJohn() will no longer result in returning `undefined`.

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

Having difficulty retrieving data when running a React JS app on the IP address 192.168.XX.XXX

I'm attempting to retrieve backend data in a React app using the Fetch API. It's functioning correctly when I run the React app on localhost, but if I change the address from localhost to an IP, it stops working and displays Unhandled Rejection ( ...

Issues with JQuery list selectors

Many individuals have raised concerns about selectors in the past, but no matter what I try, my code seems right yet it doesn't work as intended. My situation involves a list of actions that are displayed or hidden when their corresponding "folder" is ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...

How can I add an item to an array within another array in MongoDB?

I currently have a Mongoose Schema setup as follows: const UserSchema = new mongoose.Schema({ mail: { type: String, required: true }, password: { type: String, required: true }, folders: [ { folderName: { type: S ...

The Bootstrap modals seem to be invisible within the Rails application

Currently, I am integrating jquery into the devise views of a sample rails application. My intention is to test it on a sample app before implementing it in a production code. The controller and view for welcome are already set up. The routes.rb file loo ...

The tooltips on a resized jQuery Flot chart are displaying in the incorrect location

Currently, I am utilizing the flot library for my chart. I am facing an issue with getting the correct tooltips to display when I scale the chart using this CSS rule: transform: scale(0.7); The flot source relies on the function findNearbyItem to locate ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

The system has removed all content within the fields

I have created a code to generate a dynamic table. The problem I am facing is that when there are multiple rows in the table, clicking on the delete button deletes all field values instead of just deleting the data for the specific row where the delete b ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

Tips for adjusting font size automatically to fit within its parent container every time

On my blog, the post titles are displayed in a div with a video playing in the background. The length of the title varies, ranging from 2 words to over 20 words. When the title is too long, it may overflow from its parent container where the video is playi ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...

Jade not binding correctly with Angular.ErrorMessage: Angular bindings are

Struggling with simple binding in Angular and Jade. I've tried moving JavaScript references to the end of the document based on advice from previous answers, but still no luck. Any ideas on what might be wrong? File: angular.jade extends layout blo ...

Using Jquery to toggle the visibility of divs based on radio button selections

I am struggling to hide the divs with the radio buttons until their title is clicked on. However, I am facing issues as they are not showing up when their title is clicked on. Any assistance would be greatly appreciated. SPIKE <!DOCTYPE html> &l ...

Exploring the Power of v-for in Nested Objects with Vue

I currently have a dataset in the following structure: itemlist : { "dates": [ "2019-03-15", "2019-04-01", "2019-05-15" ], "id": [ "arn21", "3sa4a", "wqa99" ], "price": [ 22, 10, 31 ] } My goal is t ...

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

I specialize in optimizing blog content by omitting the final line within a React framework

https://i.stack.imgur.com/WKOXT.png Currently, I have 4 lines and the 5th line in the current input field. This is my React code snippet: import { FC, useEffect, useState } from "react"; interface BlogWitterProps {} const BlogWitter: FC<B ...

Placing the template code underneath the existing code within the Handlebars layout.hbs file

I'm currently working on a project using Express Handlebars. I have a template called foo.hbs that contains some JavaScript code which I need to insert below the script tags in the layout.hbs file: <!DOCTYPE html> <html> <head> ...

Avoid triggering the parent modal to close when a child element is clicked in VueJS

In my Vue application, there is a situation where I have a button called "detach button" with a @click function inside an element that is clickable. When clicking on this parent element, it triggers another @click function and toggles a Bootstrap modal eve ...

Dealing with Socket.io connection problems on Node.js and Windows 10 platform

Just starting with nodejs and recently set it up on my Windows10 machine. I decided to create a folder within Nodejs and included a server.js file. Next step was installing socket.io using the command "npm install socket.io". Here's a snippet of what ...