1

This is my Class

MyFunction = function(args) {
    var parameter1 = args.parameter1;
    var parameter2 = args.parameter2;
    var ObjId = args.ID;

    function getData(callback) {
        // Some code for getting data;
    }

    someFunction = function() {
        // Some calculation
    }

    someFunction2 = function() {
        //Some calculation
    }

Now I am creating two objects of this class. myObj1 and myObj2

var args1 = {
    parameter1 : "x",
    parameter2 : "Y",
    ObjId : "ID1"
}
var myObj1 = new MyFunction(args1);

var args2 = {
    parameter1 : "x",
    parameter2 : "Y",
    ObjId : "ID1"
}
var myObj2 = new MyFunction(args2);

// Third way. Don't know it is correct or not. 
new MyFunction(args2);

When I am creating myObj1 or myObj2 my code will reach to MyFunction class and all the methods inside the class like someFunction,someFunction2 and getData with reference to respective args will execute.

My question is

  1. After execute Javascript class, what happened to objects later.
  2. If all the methods present inside the will execute by var myObj1 = new MyFunction(args1); then when to use myObj1.someFunction()

Am I misiing anything ?

shanky singh
  • 1,121
  • 2
  • 12
  • 24
  • Yes, you are missing `var` declarations for your `someFunction` and `someFunction2`. Or rather, given that you want to use them as methods, [missing `this.…` property assignments](https://stackoverflow.com/q/13418669/1048572?javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) – Bergi Jul 06 '17 at 07:05
  • With your third way, nothing will happen to the object, since it's not stored anywhere so it is not accessible to call a method from it or do anything with it. – Bergi Jul 06 '17 at 07:08
  • @Bergi Thanks for the explanation about third object declaration. – shanky singh Jul 06 '17 at 07:12

1 Answers1

1

If all the methods present inside the will execute by var myObj1 = new MyFunction(args1);

That is where your understanding is wrong. No, they don't until you call them.

Function gets called only when you do

myObj1.someFunction()
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I completely agree that function gets called. and this line will create an object `myObj1 = new MyFunction(args1);` of `Myfunction` but when it goes to myfunction all the methods present in my function will execute at a same time right. – shanky singh Jul 06 '17 at 07:10
  • @shankysingh Again, they don't until you call them. – Suresh Atta Jul 06 '17 at 07:15
  • ok noted. I will try to create a fiddle if I can. Thanks for your suggestion. – shanky singh Jul 06 '17 at 07:19
  • Please check this fiddle. https://jsfiddle.net/Arsenal/vcxw24x1/1/ I passing args and creating object in html. It is executing. please have a look – shanky singh Jul 06 '17 at 07:22