The appropriate method for transferring a prototype to an object

From my perspective, prototypes work like this:

let Animal = function() {
    this.bark = "woof";
}

Animal.prototype.barkLoud = function() {
     return this.bark.toUpperCase();    
}

let x = new Animal();

x.barkLoud() = "WOOF";

I fully understand the above explanation, but then I came across a tutorial that showed what seemed to be two different ways to assign prototypes to an object. Are these methods equivalent? If so, which one is preferable?

let obj = {
    age: 45;
    __proto__: Animal
}

vs

let obj = {
   age: 45;
}

obj.prototype = Object.create(Animal.protoype);

Answer №1

It's generally advised to avoid accessing properties surrounded by underscore (_) characters in JavaScript, as they often contain implementation details that should not be modified.

While __proto__ is supported by all major browsers, it is not recommended to use it for setting up prototypes. Instead, opt for Object.create().

Additionally, the two methods you mentioned are not equivalent. The __proto__ points to the prototype object, while Animal refers to a function. To access the prototype, use Animal.prototype, which will serve as the prototype for objects created with the function and the new operator.

Therefore, the first object will not be able to find the barkLoud property in the prototype chain:

> obj.barkLoud // undefined

Answer №2

__proto__ is considered outdated and I have yet to come across any implementations of it.

It is advisable to use Object.create as the standard and suggested method for creating/assigning prototypes from existing objects to newly created ones.

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

Exploring the interactive features of discord.js version 12

Currently, I have a bot set up to log when invites are created, but the logs are only going to a specific channel ID that I designated. I would like to make it so that this can be changed on a per-server basis. Intended Output User: !log channel (CHANNEL ...

Encountered an issue with resolving the module specifier while attempting to import a module

Whenever I attempt to import a module, I consistently encounter this error message Failed to resolve module specifier "mongodb". Relative references must start with either "/", "./", or "../". and I have searched ext ...

Can you explain the inner workings of the sort function in JavaScript, including how it utilizes the compare

I'm curious about how the sort function operates in JavaScript, specifically in conjunction with the compare function. According to what I've read, if you have an array and use the code array.sort(compare), it's stated that if the compare fu ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Can inner function calls be mimicked?

Consider this scenario where a module is defined as follows: // utils.ts function innerFunction() { return 28; } function testing() { return innerFunction(); } export {testing} To write a unit test for the testing function and mock the return value ...

Extracting JavaScript variable data to PHP using Ajax technology

I've been trying to save latitude and longitude values in PHP variables, but I'm having trouble. Here is the code I'm using. Can anyone please help me figure out why these values are not being stored in PHP variables: Code: <!DOCTYPE h ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

The numerical value fluctuates upon utilizing JSON.parse( )

I am currently utilizing Node/Express to send API requests to the unofficial Vine API. The data returned by the GET https://api.vineapp.com/users/search/ route undergoes changes during parsing. This is my code snippet: request({ url: 'https://api.v ...

Fastblox - utilizing javascript SDK for group chatting

I've been facing issues setting up a group chat using QB Javascript SDK. There are a few problems I am encountering: Firstly, I consistently receive a "room is locked" message. Here's the link to the screenshot: . This is confusing as on the ser ...

Error: Unable to locate image module in REACT

Trying to troubleshoot image loading in a React project. Currently testing with an individual image, but plan to eventually store multiple images in an array for easier management. However, I'm encountering an issue where the image won't load and ...

A simple way to add a value from a select option into a textarea when there are several dropdown menus and select elements sharing the same

I have several divs with the same class names where I need to input a value from a dropdown menu into the textarea that belongs to the div where the select element is located. I want this function to work smoothly even with more than 10 divs, which is why ...

Adjust the transparency of a navigation bar independently from the transparency of the text within the navigation bar

Seeking assistance on adjusting the opacity of this navbar without affecting the text within it. Any tips on changing the text color as well? <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#" ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Having difficulty attaching events to Bootstrap 3 button radios in button.js

Struggling with extracting the correct value from a segmented control created using the radio button component of button.js in Twitter Bootstrap 3. Upon binding a click event to the segmented control and running $.serialize() on its parent form, I noticed ...

Is there a way to present both Javascript and templates from parallel directories using express?

QUERY: Is there a way to modify the server.js file so that the three.js script in index.html does not display an error message like Cannot GET /node_modules/three/three.js? Code Snippet: index.html <!DOCTYPE html> <html lang="en"> <head&g ...

What strategies can I employ to access data from an Ajax POST call beyond its original return function?

I am facing an issue with my jQuery Ajax POST call that runs a PHP script and retrieves data. The problem lies in accessing this data outside the success function. Even though I have declared a global variable components, it seems to lack scope within the ...

Organize every rectangle and text element in D3 into distinct groups

Currently, I am working on creating a bar graph using d3.js. The goal is to display text on top of each bar when the user hovers over it. To achieve this, the <text> and <rect> elements need to be grouped inside a <g> element. For Exampl ...

Configuration file stored within the node_modules directory

I have developed a generic npm package that contains my business logic. However, I require access to some information stored in my google cloud storage configuration files. How can I retrieve this data when my package is located within the node_modules fol ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...