0

I have a javascript object with a defined function

var obj = {
    addOne : function( arg1 ) { return arg1++; }
};

At an onclick event, I want to display the function as plaintext. That is to say I want to somehow get the plaintext string 'function( arg1 ) { return arg1++; }' from obj so that I can display this string in a div block.

How do?

(To be clear, I am fine with printing out the string in an html element, but unclear on how to get the desired string in the first place)

1

1 Answer 1

5
var str = obj.addOne.toString();

it's that easy

FIDDLE

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

3 Comments

In fact, that may not even be necessary because toString() is automatically called when you set a HTMLElement's textContent.
I very much enjoy when a solution turns out this simple.
@Bart - Yup, toString() is called when you try to reference a function in some place where a string is expected, but there's no harm in explicitly calling it here.

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.