What could be causing this error I'm receiving: instance versus prototype difference?

Can someone help me understand the difference between .prototype and regular instances in JavaScript? I am confused about why this code is not working and getting a type error: "undefined is not a function". I am experimenting with the Ninja() class and trying to compare it to .prototype and the first instance. Then I want to create a new instance of Ninja() called ninja and observe the differences.

     function Ninja() {
     this.swingSword = function() {
     return true;
     };
     }

     Ninja.prototype.swingSword = function() {
     return false;
     };

    var ninja = new Ninja;
    console.log(Ninja.prototype.swingSword());
    console.log(Ninja.swingSword());
    console.log(ninja.swingSword());
    console.log(ninja.prototype.swingSword());

Answer №1

Prototype is a specific property of the Function object. Since all function objects inherit from Function, they all possess this property. In the case mentioned, Ninja is a function, while ninja is an object created by Ninja. As a result, ninja does not have a prototype property, leading to a JavaScript response of undefined. Attempting to call swingSword on undefined is not feasible, hence the error message.

You can verify this by using the following code snippet:

console.log({}.toString.call(Ninja));
# [object Function]
console.log({}.toString.call(ninja));
# [object Object]
console.log(Ninja.prototype);
# { swingSword: [Function] }
console.log(ninja.prototype);
# undefined

It is important to note that the method swingSword is only defined on Ninja.prototype and not on Ninja itself. Therefore, when invoking Ninja.swingSowrd(), JavaScript will first search for it within Ninja and then in its parent's prototype, which in this case would be Function.prototype. Since lookups on Ninja do not involve Ninja.prototype, an error will occur on that particular line as well.

Answer №2

Attempting to execute Ninja.swingSword(); will result in an error because the function is not defined prior to the Ninja() constructor/function being called. However, you can achieve the desired outcome by using new Ninja.swingSword();, which will return a value of true.

It's worth noting that ninja.prototype is undefined since it's an instance of the Ninja class, and any prototype variables are directly assigned to ninja. During construction, this.swingSword is set to a new function that returns true. Consequently, calling ninja.swingSword(); will provide a result of true rather than false, as one might anticipate with the prototype function.

Answer №3

When it comes to the Ninja function, it does not actually have a swingSword method. Instead, the Ninja.prototype is where you will find this method. A function in JavaScript is essentially an object like many others, but one key difference is that you can create instances of it using the new keyword and it also comes with a built-in prototype member.

Let's say we have an object named john:

var john = {
  name: "John",
  location: {
    city: "City A",
    state: "State B"
  }
}

From this example, it becomes clear that john does not have a direct property called john.city, but it does have john.location.city as a nested property.

If you want to learn more about constructor functions and prototype in JavaScript, check out this link.

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

Tips on how to perform a server-side redirection to a different page in a Nextjs application without refreshing the page while maintaining the URL

I am working on a [slug].js page where I need to fetch data from an API to display the destination page. export async function getServerSideProps({ query, res }) { const slug = query.slug; try { const destination = await RoutingAPI.matchSlu ...

JavaScript encounters an unexpected identifier: Syntax Error

I encountered a syntax error while executing the code below: var userAnswer = prompt("Do you want to race Bieber on stage?") if userAnswer = ("yes") { console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!") } else { ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

The correlation between frames per second (FPS) and the milliseconds required to render a frame in the stats plugin is known as the frame

Recently, I've implemented the Stats.js plugin to keep track of my three.js performance. Something seems off with the FPS (frames rendered per second) and MS (milliseconds needed to render a frame) information: According to my calculations, if it ta ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

Provide two values and complete the third one

I have a form with three input fields. I want to fill out two of the fields and have the third field automatically filled in. Here is how it should work: - I fill out the first and second fields, and the third field calculates itself - I fill out ...

Disable system discord.js

Hey there, I'm experiencing an issue with my code and could use some help. Every time I try to use my mute command, it keeps spamming "You need permission to use command". Below is the snippet of my code: client.on('message', message => { ...

I am interested in retrieving a variable from a function

this is some unique HTML code <form id="upload"> <label for="file">Choose a File to Upload</label> <input type="file" id="file" accept=".json"> <butto ...

Display or conceal columns based on their index

<div ng-controller="checkBoxController"> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="moda ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Eavesdrop on outbound requests on a web page using JavaScript

As I develop a single-page application that integrates a third-party analytics tool (such as Heap, Segment, Mixpanel, etc.), I am looking to actively monitor the outgoing HTTPS requests from my app and take necessary actions, such as logging. I am curious ...

In the Opera browser, the closing script tags seem to mysteriously vanish

I recently built a website using bootstrap and implemented the JQuery load function to merge separate HTML files into one for better organization. The site is currently live on github pages. However, I've encountered an issue specifically with Opera ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...

Store the decoded user information in the database for safekeeping

I have developed an application where users can capture images and send them to the database with ease. Upon logging in, each user receives a token. As long as the token is valid, they do not need to log in again. To implement JWT authentication, I refer ...

Basic JavaScript string calculator

I'm in the process of creating a basic JavaScript calculator that prompts the user to input their name and then displays a number based on the input. Each letter in the string will correspond to a value, such as a=1 and b=2. For example, if the user e ...

Extract source, medium, etc. data from __utmz GA with the help of JavaScript

Is it possible to retrieve the campaign, source, and medium that Google Analytics records all at once when the page loads? If so, could I use jQuery to look up the values from __utmz? ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

How can I resolve the issue of <td> being repeatedly displayed five times instead of just twice in PHP?

Can someone assist me with fixing this for loop issue? I am trying to display controls next to each item in the row, but it is showing 5 sets of controls instead of just 2. <tbody> <?php //retrieve list of supplies $numOfRows = 0; $result = my ...