Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below:

function Person(name, age){
    this.name = name;
    this.age  = age;
}

Person.prototype.foo = function(){
    // do something
}

Person.prototype.foo2 = function(){
    // do something
}

var wong2 = new Person("wong2", "20");

Now, if both foo and foo2 need to call another function called foo3, where should I incorporate it?
I want foo3 to not be accessible by wong2, so adding it directly in the Person prototype is not an option.

Person.prototype.foo3 = function(){
    // Another action
}

However, defining foo3 in the global scope doesn't seem like the most elegant solution. Any suggestions on how to handle this scenario?

Answer №1

One way to create a scope where both foo1 and foo2 can access foo3 is by defining foo3 inside a closure like this:


function() {
    function foo3() { ... }
    Person.prototype.foo = function(){
       foo3();
    }

    ...

}();

Answer №2

Check out this Stack Overflow thread and read this guide on Encapsulation in JavaScript.

Answer №3

Not sure if this is the precise solution you seek, but it functions as a static method.

Person.foo3 = function() {
    // Additional functionality not inherited by wong2
}

Answer №4

Have you thought about establishing your very own unique namespace? Give it a shot!

var customNamespace = {}; 
customNamespace.createPerson=function (name,age){
   this.name=name; 
   this.age=age; 
   if (age<18){
     this.status = 'cannot Marry';
   }else{
     customNamespace.addMarriageStatus('married');
   }
}
customNamespace.addMarriageStatus = function(status){this.status=status};
customNamespace.createPerson('Jack',2);
//customNamespace

Answer №5

It seems like you are looking for a way to create a static function within the context of a specific object, in this case, the Person object, without it being accessible globally or for other instances like wong2.

To achieve this, you can simply assign a function to Person.foo3, as demonstrated below.

http://jsfiddle.net/audLd/1/

function Person(name, age){
    this.name = name;
    this.age  = age;       
}

Person.foo3 = function() {return 10;};

Person.prototype.foo = function(){
    return Person.foo3();
}

Person.prototype.foo2 = function(){
    return Person.foo3()*2;
}

var wong2 = new Person("wong2", "20");

alert("" + wong2.foo() + ", " + wong2.foo2()); //works

alert("" + Person.foo3()); //works. This demonstrates the distinction between 'static' and 'private'

alert(foo3()); //doesnt work
alert(wong2.foo3()); //doesnt work

If your goal is to implement a 'private' member using closures, that would require a different approach.

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

Saving Selected Radio button values into Jquery Array

In my HTML table, there are multiple rows with radio buttons representing the sexes in the 0th position of <td>. I am trying to store the values of sex (either 1 or 0) in an array. Below is a snippet for a table with 3 rows. HTML Code: <table> ...

Luxon: retrieve an array of time offsets and time zones (similar to what can be done in moment-timezone)

Currently, I am using the moment-timezone library to retrieve raw information for a specific timezone and then incorporating it directly into my downstream code. const zone = moment.tz.zone('Europe/London'); This data contains: { "name":"Eu ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

Does anyone know of a way to integrate a calendar feature into a React application using a library

Greetings to everyone, I trust you are all enjoying a fantastic day. I am in search of an interactive calendar similar to this one for one of my applications Does anyone know of a React library that could assist me in creating such a feature? ...

In what situations is it essential to utilize the `rerender` function in the React Testing Library?

In the past, my team and I usually focused on writing React Testing Library (RTL) tests for the main parent components that contained numerous nested child components. This approach made sense and proved to be effective. The child components in question we ...

Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this: watch: { search: function() { Crud.methods.getItems(); } }, Howe ...

The function Event.preventDefault seems ineffective when attempting to block input of CJK (Korean) characters in a v-text-field of type

Currently, I am tackling an issue in a Vue project where I need to fix a small bug. However, the solution seems quite challenging. I have managed to make the v-text-field accept only numerical input, which is functioning well. <v-text-field type=" ...

Count up with style using the "jQuery Boilerplate" plugin for Jquery!

I am a beginner in creating jQuery plugins. The following jQuery plugin has been created using jQuery Boilerplate. It performs a count-up and notifies when the count-up is completed. I would like to have a function that restarts the count-up by setting t ...

Trouble accessing onclick function

My dataSend AJAX function is not being called when I use the onclick event. I have checked in the Inspector of my browser and confirmed that the click handler is attached to it. However, when I set a breakpoint in the function using the Debugger, it never ...

Styling triangles within a CSS triangle

I'm attempting to design a webpage with a fixed triangle navigation element. The issue I am encountering is that I am unable to position smaller triangles inside the larger one, as shown in the image below. https://i.stack.imgur.com/1bTj8.png As th ...

I am looking to modify the highlighted table cell whenever the value within it changes

I am currently working on a small project related to the Stock Market. In this project, I need to dynamically change the style of the td element based on data fluctuations - green highlight for an increase and red highlight for a decrease. In the provid ...

How can I use jQuery to identify the numerical range within class/td/div elements and modify their CSS styles?

1# I need assistance in changing the CSS properties of a TD, Class, and div using a selector that specifies a specific number range. Specifically, I am looking to modify the css of torrent results with a seed count between 250-25000. Any torrents with a se ...

Associate the URL with the object to retrieve the corresponding object

When iterating through this array, I currently loop through it in the following manner: {props.choosenMovie.characters.map((characters) => ( <p>{characters}</p> /* This displays the URL of course */ ))} The URLs contain a name object th ...

Struggling with Angular 8: Attempting to utilize form data for string formatting in a service, but encountering persistent page reloading and failure to reassign variables from form values

My goal is to extract the zip code from a form, create a URL based on that zip code, make an API call using that URL, and then display the JSON data on the screen. I have successfully generated the URL and retrieved the necessary data. However, I am strug ...

When utilizing React client-side rendered components, the state may fail to update while the script is actively running

I am currently facing an issue for which I don't have a reproducible example, but let me explain what I'm trying to do: class MyComponent extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Change a Character or Word in JavaScript after it's been typed

If I were to type the word "hello" into a textarea, is there a way for me to select that specific word and modify it afterwards? For instance, let's say I typed hello without hitting the space bar; could the system recognize this word and automaticall ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Processing XML Files Using Nodejs

Apologies for the rookie question, but I'm feeling a bit confused... I'm attempting to pull "objects" from an XML file so that I can modify and incorporate them into a database. I attempted using xml2js and now have a JavaScript object, but I&ap ...

"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice. I have come across some threads discussing sending just an image, but not integrating an image within a JSON data o ...