Comparing Object.create with Object.prototype to creating a task using the Object.create method

When it comes to creating a new object, what's the rationale behind using

var task=Object.create(Object.prototype); instead of var task=Object.create(Object);

Answer №1

Within the realm of MDN Object.create(), we encounter two illustrative scenarios:

const me = Object.create(person)

Rectangle.prototype = Object.create(Shape.prototype)

A fusion of these examples results in a cohesive sample:

function Shape() {
  this.x = 0;
  this.y = 0;
  this.speak = function() {
    console.log("this is an instance function")
  }
}
// Shape.speak = ...

Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('this is a prototype function');
};

function Rectangle() { Shape.call(this); }
function Triangle() { Shape.call(this); }

Rectangle.prototype = Object.create(Shape.prototype);
Triangle.prototype = Object.create(Shape);

var rect = new Rectangle();
var tri = new Triangle();

rect.constructor // f Shape
tri.constructor // f Function

rect.speak // f speak
tri.speak // f speak

rect.move // f move
tri.move // undefined, could not access methods in Shape.prototype

The outcome of

Rectangle.prototype = Object.create(Shape.prototype)
can be expressed as
rect.__proto__.__proto__  ===  Shape.prototype

Similarly, the result of

Triangle.prototype = Object.create(Shape)
equates to
tri.__proto__.__proto__ === Shape

To delve deeper into this concept, let us explore the essence of Object.create() Polyfill

Object.create = function (proto, propertiesObject) {
  function F() {}
  F.prototype = proto;

  // (new F()).__proto__ === F.prototype === proto
  return new F(); 
};

This cascades into:

(new F()).__proto__ === F.prototype === Shape.prototype
Rectangle.prototype === new F()
rect.__proto__.__proto__ === Rectangle.prototype.__proto__  === (new F()).__proto__ === Shape.prototype

(new F()).__proto__ === F.prototype === Shape
Triangle.prototype === new F()
tri.__proto__.__proto__ === (Triangle.prototype).__proto__ === (new F()).__proto__ === Shape

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

How can Socket.io prevent other pages from receiving all messages?

I apologize for the confusing title, but I am in need of some assistance in clarifying my question. The situation is as follows: I have a website page that is receiving messages from a node server. socket.on('item finished', function(data){ ...

Encountering issues with browser tabs and Socket.IO

I'm currently working on a real-time chat using Socket.IO, but I've encountered a major issue. The aim is to allow users to log in, select another connected user, and start chatting... var http = require('http'), fs = require(&ap ...

Include an index within the array

I need to incorporate an index in my array: Here is the loop I am using: for(j=0; j< data.data.tickets.length; j++) { var created_at = data.data.tickets[j].created_at; var tickettitle = data.data.tickets[j].subject; cleartab[requesterid]['t ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

Combining routes in Express and Angular can be achieved by leveraging the power

How can I successfully integrate Jade AngularJS with ExpressJS? I have an app.js file for Express to run the server using Grunt. This app.js file renders home.jade which leads me to the home page. On the homepage, I have implemented AngularJS. I also creat ...

use react-router v4 exact prop to show both component

<Route exact path='/admin/task/create' component={ComponentA} /> <Route exact path='/admin/task/:id' component={ComponentB} /> Whenever I go to http://localhost:3000/task/123, ComponentB gets triggered. But strangely, when ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

Encountering an issue with my node configuration while working on a Discord bot

Attempting to develop my own Discord Bot has presented me with a challenging error that I am struggling to resolve: internal/modules/cjs/loader.js:968 throw err; ^ Error: Cannot find module './commands/${file}' Require stack: - C:\Users&bso ...

The JQuery condition is failing to accurately recognize the span checkbox

I am facing an issue with checking the status of a span checkbox to see if it is checked or not. For some reason, I believe that the detection of the checkbox's status is not working correctly. Below is a simplified version of my current code: ...

When using angular ui-router, the fromState will result in an empty object

While using angular ui-router, I encountered an issue where the fromState parameter was returning an empty object, while the toState was functioning correctly. I am trying to access fromState.name. This is how my controller looks: .controller('MainCt ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

Send information to the webpage through both GET and POST methods

Can data be submitted to the same page using both the GET and POST methods? Certain sensitive information needs to be sent via POST, while other data such as page_number and search_phrase should be submitted with GET. I attempted creating two forms, one ...

Tips for uploading a file using Axios in a form

When uploading a file to a Flask server, I can access files from the flask request global by using raw HTML with the following code: <form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data> < ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

Guide to incorporating rate-limiter-flexible into your current node.js express configuration

I am currently using node.js, passport, and JWT bearer token for securing my routes. However, I have yet to implement rate limiting and IP/user blocking for too many false login attempts. What is the recommended approach to integrate this into my existing ...

choosing concealed div

Struggling to target the span element within the initial item of an unsorted list, but struggling with getting the DOM structure right. <li class="chapterItem"> <a href="http://www.neuromanga.com/mangaReader.php?chapterNo=12&amp;#page ...

Leveraging the Request npm package synchronously within Meteor 1.3

In my Meteor 1.3.2.4 project, I tried utilizing the synchronous features of the request npm package. I initially followed the instructions provided in this guide article from Meteor and attempted to use Meteor.bindEnvironment. Here's the code: impor ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

I'm struggling to grasp how to effectively utilize a JSON Object in this situation

In my coding project, I am looking to utilize Javascript in order to create a JSON or array that will house pairs of data for 'id' and 'ip'. This way, if I need to retrieve the 'ip' for a specific 'id=123', I can eas ...