JavaScript: The battle of two objects - domination vs submission

Currently delving into the world of Object Oriented Programming in JavaScript, I recognize that there might be mistakes in my approach.

The main focus is on a single JS function (class) below:

function User() {
    //Code to initialize object goes here
}

//Functions
User.prototype.getEmpId = function() {
    return this.empId;
}

var myUser = new User({'empid':'1'});

console.log(myUser.getEmpId()); //Returns 1

var mynewuser = new User({'empid':'2'});

console.log(myUser.getEmpId()); //Returns 2

console.log(mynewuser.getEmpId()); //Returns 2

The issue arises from my confusion regarding why there seems to be an error. If these are indeed two separate objects, then what could be causing the conflict? You can view the complete code here.

Your assistance is greatly appreciated.

Answer №1

Each time you create a new User object, the method User.prototype.getEmpId is redefined. This means that the prototype property is common to all objects created from this constructor function.

So, what can be done in such case:

User.prototype.getEmpId = function() {
  return this.empId;
}

Answer №2

User.getEmployeeId() {
  return this.employeeId;
}

must be

User.getEmployeeId = function () {
  return this.employeeId;
}

Answer №3

Take a look at this fiddle:

http://jsfiddle.net/c5yhpav9/2/

function User(obj) {
//initializing object code here
this.empId=obj.empid;
}

//getEmpId shared for all User instances
User.prototype.getEmpId=function() {
   return this.empId;
}

var myUser = new User({'empid':'1'});

alert(myUser.getEmpId()); //Returns 1

var mynewuser = new User({'empid':'2'});

alert(myUser.getEmpId()); //Returns 1

alert(mynewuser.getEmpId()); //Returns 2

Now addressing the issue in your provided code sample, I noticed that you are setting properties/values on the User.prototype object instead of each instance of User. Below is an updated jsfiddle solution that works:

http://jsfiddle.net/L3qs4eg7/

Key Changes made:

firstly,

formUserObjectFromObject.call(this);//invoked with reference of this

and,

function formUserObjectFromObject() {
    //Called only once per object.
    for (var userKey in arg[0]) {
        switch(userKey) {
            case "appId": 
                //Invoking setAppId to set property value
                this.setAppId(arg[0][userKey]);
                break;
            case "empId":
                this.setEmpId(arg[0][userKey]);
                break;
            case "firstName":
                this.setFirstName(arg[0][userKey]);
                break;
            case "lastName":
                this.setLastName(arg[0][userKey]);
                break;
            case "roleId":
                this.setRoleId(arg[0][userKey]);
                break;
            case "emailId":
                this.setEmailId(arg[0][userKey]);
                break;
            case "supervisorId":
                this.setSupervisorId(arg[0][userKey]);
                break;
            default:
                this.setCustom(userKey, arg[0][userKey]);
                break;
        }
    }
}

I hope this explanation clarifies things for you!

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

Ways to verify if an element contains no content and then eliminate that element using jQuery

I am currently attempting to identify any h2 element within a specific div that contains no content and then delete it. Below is the HTML code I am working with: <div class="skipToContainer"> <h2 class="vidSkipTo">Hello </h2> ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

What is the limitation of including a string constant with "</script>" inside a <script> block?

I am genuinely curious about this: I thought that the following code would be valid within an HTML document: <script> var test = "<script>why? </script>"; </script> However, it turns out that this leads to an "unterminated str ...

Implement Meteor authentication with Google OAuth

I'm attempting to set up a basic login button for my Meteor app using google oauth. I followed these steps: mrt create accounts mrt add accounts-google mrt add accounts-ui I removed the default html/css/js files and instead added: client/index.html ...

Having trouble with VSCode correctly importing my main.js file

My main.js file isn't being imported in VScode and I'm at a loss for what the issue could be. Even though the index.html is adjacent to main.js, it's unable to locate it. I've successfully imported multiple js files into html in the pas ...

What is the best way to extract the primary base64 value from reader.result?

After successfully retrieving the base64 value of my file, I noticed that along with the value, I am also getting the type of file and the type of string. However, I only require the actual value in order to send it to the backend. Code for converting fil ...

Having trouble with downloading a node module?

I encountered an issue while trying to download the node-sass node module. The error message I received was as follows: To download the node-sass module, use the command: npm install --save-dev node-sass Error Binary has a problem: Error: \?\C: ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Is there a way for me to display an alert notification when a website requests access to additional storage on my computer?

Is there a way to set up an alert notification in Internet Explorer when a website requests additional storage on your computer? The notification would ask: Do you want to grant permission for this website to use additional storage on your computer? ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...

How React Utilizes Json Arrays to Add Data to a File Tree Multiple Times

For some reason, when attempting to add data to a file tree, it seems to duplicate the data sets. I'm not entirely sure why this is happening. Here's an example of the simple json array I am working with: export const treeDataFile = [{ type: & ...

Node JS encountered an error: ECONNRESET was read at TCP.onStreamRead on line 211, column 20 in the node internal stream base commons

I am facing an issue while trying to insert a large array of data into my MySQL database using node.js. Everything works fine when dealing with smaller arrays, around 300 elements, but as soon as I try to insert an array with 1 million elements, I encounte ...

Ways to access a particular property of a child component object from the parent component

Is there a way to access a child component's "meta" property from the parent component without using the emit method? I am aware of the solution involving an emit method, but I'm curious if there is a simpler approach to achieving this. // Defau ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

Using JavaScript and jQuery, apply a class when a specific radio button is checked and the data attribute meets certain criteria

Need help with changing explanation color based on correct answer selection in multiple choice question. Currently, all choices turn green instead of just the selected correct one. Any assistance is welcome, thank you. html <li class='test-questi ...

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

Utilize jQuery to append YQL output in JSON format to specific IDs in your code

I have a YQL output JSON string at this URL: Check out the YQL JSON here I encountered some other I am exploring why I am facing difficulties in extracting certain items from the returned JSON. For instance, when using jQuery to access the H1 tag within ...

The amazing property of AngularJS - Scope

I have saved this HTML code in a file. Here is the HTML : <!-- checkbox 1 --> <input type="checkbox" name="checkbox1" id="checkbox-group1" ng-model="checkbox1" value="group1"> <input type="checkbox" name="checkbox1" id="checkbox-group2" ng ...

Most effective method for including and excluding items from an array using personalized checkboxes

Is there a way to dynamically add and remove objects from an array based on the selection of custom checkboxes, along with a trigger or flag indicating if the checkbox is checked? Using the onClick function const handleFilterValues = (meta_name, meta_valu ...

Initiate a project and organize by using mongoose to sort array fields

My mongoose model for a post on a social networking platform is called PostModel: { caption: String, likes: [] // array to store information about users who liked the video, essentially referencing another model comments: [] // array to hold comment object ...