1

I am going through some JavaScript basics. Following is my code and question:

<html lang="en">
<body>
<script>
function test(){
    const printer = {
        on : true,
        mode : "black and white",
        print : printMe(" Name"),
        printAgain : function () {
            alert("Hi there!");
        }
    }
}

function printMe(name){
    alert ("Print me"+ name);
}
</script>
<input type="button" id="button1" value="Test" onclick="test()"></button>
</body>
</html>

I can call printAgain with the below line:

printer.printAgain();

But I don't need to explicitly call printMe() method. I understand that its because I am calling it in printer.print.

Is there a way to reference a javascript function inside an object and then invoke it explicitly? For example: I want the printMe() to be called when I write printer.print() in my code.

Here is the jsfiddle: https://jsfiddle.net/L8akx36j/

1
  • print : printMe(" Name"), here you are invoking the printMe() function then assigning returned value to the print property of printer object. Commented Jun 12, 2021 at 22:07

2 Answers 2

2

You can set printer.print to a reference to printMe:

function test(){
    const printer = {
        on : true,
        mode : "black and white",
        print : printMe,
        printAgain : function () {
            alert("Hi there!");
        }
    }
    printer.print(" Name");
}

function printMe(name){
    alert ("Print me"+ name);
}
<input type="button" id="button1" value="Test" onclick="test()"></button>

Sign up to request clarification or add additional context in comments.

Comments

1

Yes. You can reference a function simply by its name. Only when add parenthesis it gets called. I assume this is what you want:

const printer = {
    on : true,
    mode : "black and white",
    print : printMe,
    printAgain : function () {
        alert("Hi there!");
    }
}

5 Comments

What is the function has arguments?
Nevermind. I think I can just pass the arguments when I call.
If you do want arguments, then wrap the function in another function
Or I can just pass the arguments when I call the function as @Majed Badawi posted above.
@PKJ That's the same thing as I suggested here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.