Confusion surrounding the Javascript object prototype (utilizing require.js and three.js)

I'm feeling a bit confused about my understanding of Objects, prototypes, require.js and three.js. Let me illustrate with an example:

In Summary:

The instance "wee" is derived from "Wee," which acts as a wrapper or monkey patch for THREE...

Shouldn't "wee" then inherit properties and methods from THREE?

(Using the transitive property: a = b = c; therefore a = c.)

define (['three'], function () {
    function WEE(){
      THREE;
      return THREE;
    }
    var test = new WEE;
    console.log("test");
    console.log(test);
    function Wee(){
      WEE.call(this);
      this.prototype = new WEE();
      this.width = window.innerWidth;
      this.height = window.innerHeight;
      this.aspectRatio = window.innerWidth / window.innerHeight;
    }
    var wee = new Wee();
    console.log("wee");
    console.log(wee);
});

This is where I start to get puzzled...

The 'test' log in Chrome displays:

test
Object {REVISION: "66", CullFaceNone: 0, CullFaceBack: 1, CullFaceFront: 2, CullFaceFrontBack: 3...}

which seems correct. My intention was to create a custom version of three.js.

However, when I log 'wee' in Chrome, it shows:

wee
Wee {prototype: Object, width: 1920, height: 1102, aspectRatio: 1.7422867513611615}

Looking into the prototype details, I can see that the prototype is Wee, which relates to THREE- which is also good... but what's confusing me is when I proceed with this piece of code:

var renderer = new wee.WebGLRenderer();

and it gives back "undefined".

I've also attempted:

var renderer = wee.WebGLRenderer;
var renderer = wee.WebGLRenderer();

but all attempts fail with "Uncaught TypeError: undefined is not a function."

Questions:

  1. What could be happening here?
  2. What key element am I overlooking?
  3. Why does THREE actually work initially, given that my define function requires it but doesn't assign it anywhere?
  4. Am I even asking the right question? Is there a better way to phrase it so I can search for answers more effectively next time?

Answer №1

Within this excerpt:

this.prototype = new WEE();

The code snippet above creates a property named prototype on the object, but it does not actually set the underlying prototype of the object itself (which is not named prototype; it currently remains anonymous in the standard although some implementations refer to it as __proto__). It could have just as easily been labeled as robert.

In JavaScript, the prototype of an object can be established using one of two methods:

  1. When you instantiate an object using new FunctionName, its prototype is derived from what FunctionName.prototype points to at the time of instantiation with the new operator.

  2. If you create the object via Object.create, then the specified prototype is directly assigned within the Object.create method call.

For instance:

function Foo() {
}
Foo.prototype = {
    bar: 42
};
var f = new Foo();
console.log(f.bar); // 42

And also:

var f = Object.create({
    bar: 42
});
console.log(f.bar); // 42

However, it's important to note:

function Foo() {
    this.prototype = {
        bar: 42
    };
}
var f = new Foo();
console.log(f.bar);           // undefined
console.log(f.prototype.bar); // 42

It should be emphasized that adding a prototype property to an instance created by new Foo does not impact setting the prototype of said instance.

This exemplifies one of the common misunderstandings in JavaScript: The prototype property found on functions is not related to the function's own prototype; rather, it dictates the prototype applied when utilizing the new operator with that function. Objects do not possess any named property representing their prototypes (at least for now, across different JavaScript engine implementations).

Looking ahead to ES6 (the forthcoming version of the specification), the __proto__ property accessor is expected to enable direct access and manipulation of an object's prototype. While supported in existing engines like SpiderMonkey (used in Firefox), it has yet to become standardized.

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

An entity becomes trapped in an endless cycle

I am revisiting the concept of OOP with a simple idea but it has been a while since I last worked on something like this. class UserAPI { protected $Email; protected $APIKey; public function setEmail($e) { $this->Email = $e; ...

clicking on an element to get its div id

In my code snippet $('.startb').click(function() { var myId = $(this).attr("id"); });, I am already capturing the id "startb1". To also capture the id "test1" from the element with the class "flashObj", all within the same div container "audioCon ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

When attempting to transfer data to a CSV file from my Firebase database, I encounter an issue where the

I am facing an issue with exporting data from my Firebase Firestore to a .csv file. I have followed all the necessary steps, but whenever I try to add the values for export, they show up as undefined. While I am not an expert in React and consider myself ...

What is preventing me from getting jQuery UI 1.8.20 dialog to function on JSFiddle?

My attempt to implement jQuery UI dialog in JSFiddle has been unsuccessful, consistently resulting in a dialog opening error caused by a deep-seated issue within jQuery UI: Uncaught TypeError: Cannot read property '3' of undefined. Although I am ...

Instructions for receiving user input and displaying it on the screen, as well as allowing others with access to the URL to view the shared input provided by the original user

<h1>Lalan</h1> <input type="text" name="text" id="text" maxlength="12"> <label for="text"> Please enter your name here</label> <br><input type="submit" value ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel </pre> Input: import React, { useState } from "react"; import ...

Understanding the variations in behavior of the history.go(-1) method across various browsers

Is history.go(-1); consistent across all browsers? I've noticed different behaviors on various browsers. In my code, I have a line similar to javascript:history.go(-1); On the first page, there are three checkboxes. Users can only select two of them ...

The package 'models' imported from is not found [ERR_MODULE_NOT_FOUND] error

I'm currently in the process of setting up my project to utilize absolute imports. To accomplish this, I've made adjustments to my jsconfig.json file as shown below: { "compilerOptions": { "baseUrl": "./src&quo ...

Is there a way to incorporate logic into my Angular routes?

I am looking to secure certain routes within 'case' sections based on the dependency of $scope variables (whether forms are valid or not). var loginForm = angular.module('loginForm',[ 'ngRoute', 'stepsControllers&apo ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

Executing DDD encapsulation techniques

I'm hoping that I'm on the right track with this question, as I couldn't find the answer through my research. So, hopefully someone can help me here. I've recently started working with Laravel and came across a new design approach call ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

By default, make the initial element of the list the selected option in an AngularJS select input

I'm running into an issue with setting the first element in my ng-repeat list within a select input. Here is the code snippet causing the problem: <div> <span >OF</span> <select ng-model="eclatementCourante.ordreFabricationId" n ...

The issue of undefined return for multiple columns in MVC when using MCAutocomplete Jquery UI

My MVC multiple column is returning undefined. What am I missing or what is wrong with my code? Please help. https://i.sstatic.net/euwe8.png Controller public ActionResult EmployeeIDSearch(string term) { // Get Tags from data ...

Tips for preventing child elements from becoming distorted when the parent element is resized

How can I prevent rotated child elements from skewing when the parent element is scaled? Here is the code snippet that I am working with: <svg viewbox="0 0 500 500"> <g class="parent" transform="matrix(1.71341 0 0 1 -42.302 0)"> <path ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...

Parcel Bundler works perfectly fine on localhost, however, an error is being displayed on the index.html file in the Dist folder

Currently, I am in the process of learning how to use Parcel for bundling purposes. I have set up a index.html file that is connected with index.js. Surprisingly, everything works perfectly fine when I access it via localhost:1234 using Parcel. However, wh ...