Tom Avni
Tom Avni

Reputation: 149

JavaScript/ return an object in function

I have an object with 3 fields: num which int, str which string and arr which array. So I define it:

function myClass(num, str, arr) {
   this.num = num;
   this.str = str;
   this.arr =arr;
}

Now I have function, which it return value is myClass. This function get string:

function myfunc(str){
   var str1 = str.split(" ");
   return myClass(1, str1[0], str1);
}

but when I run it, it returns undefine. How I return the myClass object?

Upvotes: 0

Views: 181

Answers (3)

Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2411

function myfunc(str){
   var str1 = str.split(" ");
   return new myClass(1, str1[0], str1);//add new keyword here
}

The new keyword will produce an object to which the keyword this will refer to.

Upvotes: -1

Alnitak
Alnitak

Reputation: 340055

You need to return new myClass(...)

Without the new keyword, the myClass function just acts like a plain function that doesn't return anything (hence undefined).

With the new keyword, a new object will be created and passed as this, and that same object will be the default return value.

Upvotes: 4

Paul
Paul

Reputation: 141927

You're missing the new keyword:

function myfunc(str){
   var str1 = str.split(" ");
   return new myClass(1, str1[0], str1);
}

Upvotes: 5

Related Questions