miserable
miserable

Reputation: 727

Call JavaScript function inside an object

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/

Upvotes: 1

Views: 594

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28404

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>

Upvotes: 2

Evert
Evert

Reputation: 99495

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!");
    }
}

Upvotes: 1

Related Questions