Invoke this (public) function from within a private function

This is the JavaScript code I am working with: (Check it here)

$(function () {
    function Cat()
    {  
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();    
        }

        var MakeNoise = function () {
            Meow("noise");
            //Cat.Meow("noise");
            //self.Meow("noise");
            //this.Meow("noise");                      
        }        
    }

    var c = new Cat();
    c.Kick();
});​

When trying to call the Kick function, an error "Meow is not defined" keeps popping up. This occurs no matter which method I use in the MakeNoise function.

I've also attempted to use prototyping but faced the same error:

Cat.prototype.Meow = function (sound) {
    return this.Meow(sound);    
}

I believe there must be a simple solution to this problem, but I'm struggling to successfully invoke the Meow function of the "Cat" class. Any suggestions on how to accomplish this?

Additionally, does this design structure even make sense? My goal was to have Kick and Meow as public functions, and MakeNoise as private.

Answer №1

Store an object reference to be utilized in the MakeNoise function.

$(function () {
    function Cat()
    {  
        var self = this;
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();    
        }

        var MakeNoise = function () {
            //Meow("noise");
            //Cat.Meow("noise");
            self.Meow("noise");
            //this.Meow("noise");                      
        }        
    }

    var c = new Cat();
    c.Kick();
});​

http://jsfiddle.net/mowglisanu/7XEYD/3/

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

What is the best way to incorporate multiple JS files into Rails 6 using a template that I came across on the web

So, here's the dilemma... I've spent almost a month on this project and I'm at a loss for what to do next. I came across a fantastic Bootstrap theme online that includes a plethora of JavaScript files. Wanting to build the website in Rails 6 ...

Tips for properly encoding SQL search results so they can be decoded in JavaScript and utilized in various div containers

I have been working with a SQL database that includes a 'title' column. The function I created below is intended to be passed back through AJAX for display purposes. My goal was to retrieve the entire contents of the title column and store it in ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...

Deactivate Bootstrap Button Pills and Activate Change with an Alternate Button

Seeking a solution for my multi-step form utilizing Bootstrap nav-pills. Currently, users can navigate through the steps without completing the required form fields first. I am looking to disable this feature and trigger content changes with a different bu ...

What is the best way to initiate an event from a control within a GridView?

I need help with triggering an event to reset the text of a label. Within my GridView, I have a row defined like so: <asp:TextBox ID="txtgvEmailAddress" Text = '<%# Eval("EMAIL")%>' runat="server" Width="200px" onclick="ResetMessage()" ...

Is there a way to store my collection data in a variable and access it externally from the file?

Topic of Interest : Working with Discord.js I am seeking advice on how to save collector data in a variable and access it outside of the file, for example in index.js. I aim to create a setup command that prompts users with questions when they type -setup ...

Prevent selection of future dates in JavaScript by using the user's chosen StartDate

Here is the code I currently have: var today = new Date().toISOString().split('T')[0]; document.getElementsByName("StartDate")[0].setAttribute('min', today); $('#StartDate').change(function myfunction() { var endDate = ...

What is the best way to generate dynamic components on the fly in ReactJS?

Could you please guide me on: Techniques to dynamically create react components, such as from simple objects? Is it possible to implement dynamic creation in JSX as well? Does react provide a method to retrieve a component after its creation, maybe b ...

AJAX submission of tinyMCE content - Encoding of special characters within table elements

Currently, I am integrating the tinyMCE editor plugin into my website. When I utilize a basic HTML page post to send the content to the backend PHP for saving it into a database or file, everything works fine. However, when I attempt to achieve the same ...

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

Understanding JavaScript's Inheritance

My current Person class looks like this: class Person { constructor(name, age, gender, interests) { Object.assign(this, {name, age, gender, interests}); } } I have also created a sub-class Teacher which inherits properties from the Perso ...

Step-by-step guide to automatically submitting a form after obtaining geolocation without the need for manual button-clicking

I am looking for a way to automatically call a page to get geolocation data, and then submit the form to my PHP page with the values of getlat and getlon without the need to click a submit button. I have tried implementing the code below, however, despit ...

How does assigning a checkbox's value as 'undefined' result in the addition of ng-invalid?

I'm facing an issue with a checkbox in my Angular project. The checkbox has a false value of undefined, and even though it's not marked as required, the form doesn't validate when I check and uncheck it. This is because the class ng-invalid ...

Using JavaScript to animate a background composed of SVG shapes

My code is successfully adding an svg background with js and rotating it using set interval. It works perfectly on Chrome, but not on any other browser. Any suggestions on how to make it work universally? let i = 0; setInterval(() => { document.b ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Adding a marker to Google Maps in React that displays the user's current location

I successfully integrated Google Maps into my website and now I want to add a marker for the user's location. The first file is Map.js, and the second one is MapContainer.js. In MapContainer.js, I have all the necessary data for map rendering, includi ...

Mastering Knockout: Extracting the selected value from a dropdown and transferring it to an AJAX request

http://jsfiddle.net/smihit_123/kopp8h53/ self.selectedCity.subscribe(function () { alert("this is percentage" + this.percentBonus); }) Is there a way to retrieve the value of an observable property in knockout? For instance, in the jsfiddle ...

Angular's separate scope variables allow for isolated data manipulation within individual components

Struggling with one scope variable affecting multiple elements in a div in AngularJS. Looking for help as a beginner in handling this issue. For a clearer understanding, here's an example: JS: /* controller-home.js ********************************* ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Is it possible to halt code execution in Node JS after sending a response?

I am currently learning Node JS and practicing to develop a MERN app. I have implemented two middleware functions named getUserById and isSignedIn. router.param("userId",getUserById) const getUserById = (req,res,next,id)=>{ User.findById( ...