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

Compare the selected values of radio buttons with an array and find matches

I have multiple radio button groups, where each selection in a group corresponds to predefined values in an array. For example, selecting option 1 in Group 1 will increment values A and B by 1, while selecting option 2 will increment B, C, and D. The goal ...

An unrecoverable error has occurred in the SetForm function: PHPMailer::SetForm() method is not defined

While working on form validation in jQuery with a WAMP server, I encountered two errors: Fatal error: Uncaught Error: Call to undefined method PHPMailer:: SetForm() and Error: Call to undefined method PHPMailer::SetForm(). I have already added PHPMailerAu ...

Exploring unescaped XML for handling unicode characters

Currently tackling the challenge of parsing some XML that is not properly formatted. The XML file contains un-escaped ampersands, which goes against the standard rules for XML files. My goal is to extract unicode formatted phrases from this XML file whil ...

There seems to be a glitch in the functionality of annotations when using annotator.js

Currently, I am utilizing annotator.js to store the range in mysql. The following code fragment is being used for highlighting text within my file: <script src="/js/pdfjs/annotator.js"></script> <script> $(function(){ var annotation ...

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Looking to create dynamic pages on NextJS without relying on fixed paths?

I am looking to create a unique user experience by offering discounts on my website based on the users' citizenship ID numbers. By using their ID number, I can customize the discount amount according to factors such as location, age, and gender. User ...

The addition of a cancel swipe feature to an HTML5 eBook is causing the text input field for note-taking to malfunction

I am currently working on the development of a process to create HTML5 based eBooks for both desktop and mobile use using Adobe InDesign and exporting them with a plugin called In5. This plugin allows for the incorporation of html, css, and javascript duri ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

What is the best way to clear an array?

Yesterday I had a query regarding JSON Check out this link for details: How to return an array from jQuery ajax success function and use it in a loop? One of the suggested answers included this script: setInterval(updateTimestamps,30000); var ids = new ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

The component data fails to reflect the updated value following a status change due to not properly retrieving the new result from the POST function

Below is the Vue.js 2 code snippet for sending data to the backend. The vuex library was used to manage the data status. After using the POST function, the result returned from the backend updates the value of sampleId. This value is auto-generated by the ...

CORS problem in Chrome when using AngularJS and Symfony 3

I've been dealing with a bug on my backend and frontend for the past week. I created a REST API (php/symfony) to manage books and authors. Initially, I had trouble with cross-origin requests on DELETE, which has been resolved. However, now I am facin ...

What is the established procedure for resetting all elements within an (X)HTML document?

Is there a way to reset elements without using a form like how it can be done with JavaScript? document.forms[0].reset(); I am utilizing AJAX, so do I need to loop through all the elements using JavaScript? ...

Forgetting your password with React JS

On my login page, there is a button labeled "Forget my password". When I click on this button, I want to be taken directly to the correct page for resetting my password. Currently, when I click on "forget my password", it displays beneath the login sectio ...

Error: Syntax mishap detected - Oh dear

Recently, I've been developing a small slideshow / public display for a client using the HTML5 Rock's Slideshow code. Everything was going smoothly until I encountered a DOM Exception 12 - an error related to CSS selectors. Strangely, I couldn&ap ...

What is the best way to retrieve the values of "qty" and "price" and access them within the item [array] without knowing the IDs?

I am currently working on a shopping cart project, specifically on the "previous orders" page to display order details. My goal is to output this information in an (.ejs) file. The data structure includes nested objects, and within one object, propertie ...

Every time I enter npm start in the terminal, I consistently encounter this error

After developing a simple web app and posting it on my repository, I started encountering these persistent errors. npm ERR! code ELIFECYCLE – David 1 hour ago npm ERR! syscall spawn C:\Windows\system32\cmd.exe;C:\Users'usernam ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

Tips for choosing option values from the browser console in Angular

Is there a way to choose one of the list values directly from the browser console? I appreciate any assistance provided <select style="width: 100%" id="Select1" class="css-dropdowns ng-not-empty ng-dirty ng-valid ng-valid-required n ...