JavaScript's Object.prototype has not been defined

In my quest to create a flexible "class" in JavaScript, I encountered an issue when trying to assign a property in a prototype as it showed that the prototype was undefined:

Class = {};
Class.extend = function(obj) {
    var result = Object.create(this);

    if (obj) {
        for (var key in obj) {
          if(typeof obj[key] == 'function'){
            console.log(result);
            result.protorype[key] = obj[key];
          }else{
            result[key] = obj[key];
          };
        };

        result.prototype.constructor = result;
    }

    return result;

}

var a = Class.extend({
    username: "matteo",
    password: "nn te la dico",
    getByUsername: function() {
        return this.username;
    }
});



console.log(a, Class.isPrototypeOf(a));​

The issue arises specifically when attempting to set the property 'getByUsername' while defining object "a". The console outputs:

Uncaught TypeError: Cannot set property 'getByUsername' of undefined 

Meanwhile, the logged "result" only shows the properties "username" and "password".

P.S. This implementation is compatible only with IE versions above 8.

Link to the code: http://jsfiddle.net/paglia_s/z62eA/

Answer №1

Avoid creating your object like this: Class = {};

Instead, create it like so: Class = function(){};

This will generate a new object with a prototype.

Your code should resemble the following:

Class = function(){};

Class.extend = function(obj) {
    var result = Object.create(this);

    if (obj) {
        for (var key in obj) {
          if(typeof obj[key] == 'function'){
            console.log(result);
            result.prototype[key] = obj[key];
          }else{
            result[key] = obj[key];
          };
        };

        result.prototype.constructor = result;
    }

    return result;

}

var a = Class.extend({
    username: "matteo",
    password: "nn te la dico",
    getByUsername: function() {
        return this.username;
    }
});


console.log(a, Class.isPrototypeOf(a));​

Answer №2

There is a mistake in your code. The correct syntax should be result.prototype[key] instead of result.protorype[key]

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

Is it possible to utilize AngularJS's $q functionality outside of an Angular component?

I am currently working on a browser application, where I have a specific file responsible for creating and initializing an object. This file is written in plain Javascript rather than being part of the Angular ecosystem like the rest of the app, which is b ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

Optimal Placement of CSS and index.html Files in ReactJS with Redux

Currently, my setup for the index.html file looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pra ...

To trigger a method in a VueJS parent component, one can utilize event listening

In my VueJS 2 project, there are a parent component and a child component. The parent component sends a property named items to the child component. Whenever the user clicks on a button within the child component, it emits a refresh event using this synta ...

Exploring Data Source in Angular through Iteration

I am looking to create a function that will loop through an array of objects and update the status property to false. This array of objects is being used as a data source in an Angular table. this.lightService.getLamp() .subscribe( (response) => ...

Moving data of a row from one table to another in Laravel by triggering a button click

For instance, consider a scenario where clicking a button moves a row to another table in the database and then deletes it. Implementing this functionality in Laravel seems challenging as I am unable to find any relevant resources or guidance on how to pro ...

Is the availability of XMLHttpRequest constant?

When using XMLHttpRequest to retrieve data from the server with Javascript, is it necessary to include conditional checks for the specific browser being used? Is the code snippet below considered standard practice when working with XMLHttpRequest? if (w ...

Tips for automatically activating the HTML select menu on an iPad

My website features a suburb lookup tool that allows users to input a suburb or postcode (Australian only, e.g. 4000, 2000, Brisbane, Sydney etc) and receive the corresponding suburb/state/postcode in a select menu format: <select size="4" name="contac ...

What is the best way to create floating text that appears when clicked, similar to the mechanics

https://i.stack.imgur.com/nRKG1.jpg Upon clicking the "big cookie" in my game, a popup appears displaying the number of cookies earned (like +276.341 septillion in this image). The popup slowly moves upward and then fades out. I successfully incorporated ...

The date range picker displays the previous arrow but not the next arrow

I am currently using the DateRangePicker tool and for some reason, I am not seeing the arrow that should appear on the right side. I have double-checked my configuration but can't seem to figure out what is causing this issue. In the image attached, ...

Retrieving a data value using a specific key within a JavaScript object

Trying to retrieve a specific value by providing the literal key in a JavaScript object. The image below indicates that "filter" is equal to "Approved", sourced from reimb_status_description. Line 6 of code assigns filter to the value. const filter = Obj ...

The CSS style of the Div element is not being displayed properly when embedded with JavaScript

Currently, I am working on a simple page for practice purposes. The main issue I am facing is with a div element that has a red border and a blue background. Inside the div, there is a script tag calling an external JavaScript file. Surprisingly, the JavaS ...

Alter the attributes of an instance in a class using a function

Attempting to explain a simple method in TypeScript. This method should allow modification of data for any object type within the data attribute. In simpler terms, we can modify, add, or remove data based on the specified data type, and TypeScript facilit ...

Arranging an array of numeric values without utilizing the sort() function

Currently learning Javascript and I'm facing a challenge in an exercise from a tutorial, think it was learn street.com... The task is to sort an array of numbers without using the sort() method. Array looks like this: numbers =[12,10,15,11,14,13,16]; ...

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

Redirecting files from the file system to the emulator is not functioning properly

I am new to Phonegap and need help resolving this issue. In my application, I need to redirect to the List.html file when a button is clicked. Here is the code I have written: button1 function test() { window.location="/home/swift-03/phonegapexa ...

Error: Query is not valid

I'm encountering an error when trying to run this query, and I'm not sure why it's returning a bad request. My goal is to fetch a specific user from the database using the accountId. Can someone assist me with this issue? Below is the funct ...

The margin of the parent container is influencing the margin of the child element

Purple Working on displaying a rectangle shape in a browser using divs in my React project. Everything works fine, but when I add margin to the parent base and then draw the boxes, there's some space between the mouse cursor and the actual box. The ...

Rendering a dynamic 3D model with animated sequences in Three.js through CreateFromMorphTargetSequence

When attempting to load a GBL file and play the animation, I encountered the following error message: TypeError: Cannot read property 'length' of undefined at Function.CreateFromMorphTargetSequence function Animate() { if(window.anim_flag) ...

How to update data in AngularJS grid component using ng-bind directive

As a newcomer to AngularJS, I'm facing an issue that I need help with. Here's my problem: I have an ng-grid connected to a table. Inside the grid, there are values along with an ID (which is a foreign key from another table). Instead of display ...