# Best practice to call functions?

**URL:** <https://discourse.nodered.org/t/best-practice-to-call-functions/36103>\
**Category:** Developing Nodes\
**Created:** [17 November 2020 22:58 UTC](https://discourse.nodered.org/t/best-practice-to-call-functions/36103 "2020-11-17T22:58:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Norberg95](https://avatars.discourse-cdn.com/v4/letter/n/848f3c/32.png) [@Norberg95](https://discourse.nodered.org/u/Norberg95)\
**Post date:** [17 November 2020 22:58 UTC](https://discourse.nodered.org/t/best-practice-to-call-functions/36103/1 "2020-11-17T22:58:19Z")

</div>

Currently I have an app and I embedded node-red. I am making nodes for Classes in my app, and when I am adding a node to the flow, a new instance of the class is initialized.  
What is the best practice to call the class functions?  
Lets say I have a setLevel() and a setColor() function.

```auto
this.on('input', function(msg, send, done) {
		if(msg.topic=="setLevel"){

			setLevel(msg.payload)
		}
		else if(msg.topic=="setColor"){
			setColor(msg.payload)
		}
	  });

```

Is it viable?

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [17 November 2020 23:32 UTC](https://discourse.nodered.org/t/best-practice-to-call-functions/36103/2 "2020-11-17T23:32:30Z")

</div>

> [@Norberg95](#):
>
> Is it viable?

I dont see anything wrong (other than you arent calling a member function e.g...

```JavaScript
      //somehere at the top of the node-red node
      var myInstance = new MyClass()

```

```auto
      // later on...
      this.on('input', function(msg, send, done) {
		if(msg.topic=="setLevel"){
			myInstance.setLevel(msg.payload)
		}
		else if(msg.topic=="setColor"){
			myInstance.setColor(msg.payload)
		}
	  })

```

or you could hold of on initialisation until it is used,,,

```JavaScript
      //somehere at the top of the node-red node
      var myInstance;

```

```auto
      // later on...
      this.on('input', function(msg, send, done) {
        if(!myInstance) myInstance = new MyClass();
		if(msg.topic=="setLevel"){
			myInstance.setLevel(msg.payload)
		}
		else if(msg.topic=="setColor"){
			myInstance.setColor(msg.payload)
		}
	  })

```

What is it you are concerned about?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [16 January 2021 23:32 UTC](https://discourse.nodered.org/t/best-practice-to-call-functions/36103/3 "2021-01-16T23:32:44Z")

</div>

Closed on 16 January 2021 23:32 UTC

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.
