0

I'm new to javascript and after looking a little into javascript scoping and garbage collection, I'm still unsure about what is the right way of doing this.

I want to have a function whose job is to create an object with certain properties and return it. My worry is whether the object created in the function would go out of scope and get dumped. So basically which of the following is better, or are they both wrong?

    function createObject() {
            var obj = new MyObject();
            // set some object properties here
            return obj;
    }

    function createObject2(object) {
            // set properties of the input object here
    }

I would call my functions like so:

    myOjbect = createObject();
    myOjbect2 = new MyObject();
    createObject2(myObject2);

Basically I'd prefer the first way, but would I have to worry about garbage collection and would it be better to pass a reference of my object into the function instead of creating my object in the function itself?

1
  • 1
    Garbage collection in javascript only happens when you break all references to an object. Commented Jan 28, 2014 at 8:02

2 Answers 2

4

Basically I'd prefer the first way, but would I have to worry about garbage collection

No. When you do

myOjbect = createObject();

then myOjbect reference the object created inside the function. As long as this variable "exists" and keeps a reference to the object, it won't be garbage collected.

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

Comments

0

The first one is better. You can set everything you want inside the function. If you return it will be avaliable in the calling scope.

var createObj = function(name) {
     var age = 13;
     var hidden = "hello";
     return {
        age : age,      //you can refer a var from this function
        name : name,    //you can use params
        gender : "male" //you can set new properties
     };
}

var myObj1 = createObj("Penguinator");

console.log(myObj1.name);
//Will output --> Penguinator

console.log(myObj1.age);
//Will output --> 13

console.log(myObj1.male);
//Will output --> "male"

console.log(myObj1.hidden);
//Will output --> undefined   <<-- you can't access this var

1 Comment

I don't think Penguinator intends to create a new object in createObj. It looks like he wants to modify a custom object. MyObject

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.