Click here to Skip to main content
16,022,069 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I'm implementing a simple toast notification system using JS. This is my code:
JavaScript
const notify = {

success(text) {
	this.show("success", text);
},

error(text) {
	this.show("error", text);
},

show(type, text) {
	// Create a div element containing text. Here "success" and "error" are CSS classes applied to that div.
}

};

notify.success("Done!");
notify.error("Something went wrong");

Is it really necessary to create the first two methods (success and error), or there's a way to know which of them has been invoked and then pass it as an argument (type) to show method? I mean something like this:
JavaScript
const notify = {

type: this.called,

text: type(text),

show(type, text) {
	// Create a div element containing text. Here "success" and "error" are CSS classes applied to that div.
}

};


What I have tried:

JavaScript
const notify = {

type: this.called,

text: type(text),

show(type, text) {
	// Create a div element containing text. Here "success" and "error" are CSS classes applied to that div.
}

};
Posted
Updated 25-Aug-24 8:52am
v2

1 solution

I haven't tried this but you might be able to accomplish this using argument.callee.caller[^].
 
Share this answer
 
Comments
LB2371 26-Aug-24 2:09am    
Did you read that MDN page before posting your answer?
Dave Kreskowiak 26-Aug-24 8:01am    
Do you understand what the word "might" means?

After reading that page, I'm assuming you might need to rethink and rewrite your code to implement the suggestion.
LB2371 26-Aug-24 9:28am    
Don't you understand that your reply is as useless as the "answer" above? My question is: is there a way to know which method has been invoked?. Possible answers: 1) no, there is not; 2) yes, there is - it's this... Then I'll decide if and how I want to "rethink and rewrite" my code. I don't need lessons/suggestions: I just need a specific answer to a specific question.
Dave Kreskowiak 26-Aug-24 9:35am    
Have a nice life!
Pete O'Hanlon 27-Aug-24 4:40am    
An alternate approach would be to play around with console.trace (there's also an Error.trace option if that doesn't work for you), which produces the stack trace. As long as you aren't mangling calls using something like webpack, you should be okay here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900