2

I am kind of back engineering a javascript project and need to inject a function into some already writeen code.

I want to be able to call something like the following function in javascript:

human.mouth.shout(word);

So this would call the function that makes the object 'shout'.

My question is, how I create child attributes of the human object. As far as I know, I can only have one nested function in javascript, so at the most basic I have something like this:

function HumanObj(){
    this.shout = function(word){
        alert(word);
    }
}

Then to call this, I would use:

var human = new HumanObj;
human.shout("HELLO WORLD");

So this would give us our alert: "HELLO WORLD".

So how would I break this up so I could call it using the following?

var human = new HumanObj;
human.mouth.shout("HELLO WORLD");

Have tried this, but didn't work - assume you can't have too many levels of nested functions...

function HumanObj(){
    this.mouth = function(){
         this.shout = function(word){
            alert(word);
        }
    }
}

Thanks!

1 Answer 1

4

You can do:

function HumanObj(){
    this.mouth = {
        shout: function(word){
            alert(word);
        }
    };
}

Or if you need mouth to be instantiatable (with additional stuff in its prototype), you can do:

function HumanObj(){
    function mouthObj() {
        this.shout = function(word){
            alert(word);
        }
    }
    this.mouth = new mouthObj();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Top way worked great. Sorry I don't have quite enough rep to vote you up, but thanks for the help.
@web_la - Thats never an issue. Gald it helped. :-)
@web_la You can't vote up, but you can accept the answer by click on the little tick mark. That's worth much more than an upvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.