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

Finding the latitude and longitude coordinates of a point at a specific distance from another using Node.js or JavaScript

My task involves determining the square area based on a latitude and longitude (x,y) as shown in the provided figure. To accomplish this, I must calculate the coordinates of the remaining three corners by adding 10 kilometers to each side. I will be using ...

What is the best way to apply a texture to a triangle using three.js?

I've been able to add textures to cubes, spheres, and other primitives in a scene I created. However, when it comes to adding a texture to a simple triangle, I'm encountering difficulties. Below is my attempt at achieving this: var texture=TH ...

Emulate the utf8_general_ci collation in mysql database

I am in the process of integrating a javascript application with a third-party API that manages names in a database. The challenge I am facing is that the third-party application uses utf8_general_ci collation to determine name uniqueness, while my applica ...

Utilizing JavaScript regex to remove substrings that contain parentheses

I am working with a string variable named myString that includes some unwanted content towards the end: var myString = 'The sentence is good up to here foo (bar1 bar2)'; var toBeRemoved = 'foo (bar1 bar2)'; I am looking for the best w ...

"Using a triangular background shape in JavaScript instead of a traditional circular

I want to add a unique effect to my site inspired by the AnimatedHeaderBackgrounds demo available at this link. My twist on this effect involves using upward-moving triangles instead of circles. I've explored various resources, including Stack Overfl ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Strange state manipulation in React JS using MaterialUI

Having trouble displaying an input component from material-ui, as it crashes the page when I type a few letters. import React from 'react'; import Input from '@material-ui/core/Input'; export default function ComposedTextField() { ...

The default skin of video.js is disrupted by a 16:8 ratio

Incorporating videojs into my react application has presented a challenge. I have enclosed the video player in a div set to a 16:8 ratio, but unfortunately the default skin does not display properly. On the other hand, when I implement code that includes t ...

A guide on expanding MaterialUI Accordion in React by clicking on a different component

I am trying to implement a feature where clicking on a marker on a map will expand the corresponding accordion item. Both markers and accordion items have matching key values as seen in the screenshot below. The code I currently have uses the Map() functi ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

"if the condition is not met, the outcome will not be shown in the while

I have a looping structure that includes conditions for if, else if, and else. However, I have noticed that the else condition at the end of the loop is not being executed as expected. I am currently investigating why this might be happening. Here is the ...

Error: The text value is not defined

Hello, I am currently working on retrieving the selected value of an input when the input is focused with the tab key. Below is my code: HTML <input id='texteb' type="text" value='' /> <button> click </button> JS ...

What is the method for duplicating the HTML code of multiple elements in the Chrome console?

Is there a way to easily copy all the HTML code from elements that have the "abc" class? I attempted using $('.abc') in the Chrome DevTools console, but it only returns an array that I can't expand and copy all at once... Any suggestions on ...

Identify all elements that possess a specific attribute with a precise value in jQuery, and return either true or false

I'm having a slight issue with jQuery. Below is the code in question: if ($("select[rendelo='" + rendelo + "'][nap='" + nap + "'][napszak='" + napszak + "']").val() == 0) { alert('sth'); ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Obtaining page information from a frame script in e10s-enabled Firefox: A guide

One of the challenges I'm facing is with my Firefox extension, where a function loads page information using the following code: var title = content.document.title; var url = content.document.location.href; However, with the implementation of multi- ...

What is the best way to enable a child category on a treeview within a Vue component?

I am working with two vue components. The first component (parent component) looks like this: <template> ... <ul class="filter-category" v-for="list in categories"> <list-category :data="list" :category-id="category ...

Numerous status buttons with a variety of background colors

There are 3 buttons on the order page: [New Order], [Processing], and [Completed]. When the processing button is clicked, the background of the button should change and the order status will be updated in the database. The [New Order] button will have a ...

What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png When I click on the tab, it expands like this https://i.stack.imgur.com/XNuBi.png After expanding, I want the svg icon to change to something e ...