1

Suppose we have an object foo

var foo = {
 x: 0
}

And we add a function fx to it like this:

foo.fx = function() {do_something(this.x)}

If we do this process in a loop or in a function call for multiple times, does the JavaScript engine create that fx function multiple times or does it create the function for once and just change address of this?

e.g

function objectMaker() {
     function fx() {
         this.x += 1; 
     } 

     var foo = {
        x: 0,
        fx: fx
     } 

     return foo;
}

Does the objectMaker function always allocate memory for fx method or does it create it only once?

2
  • I guess modern JS engines avoid wasting memory by recreating the same object multiple times, but it's hard to be sure. Commented Dec 10, 2019 at 16:14
  • In your example with function I think that on each call of objectMaker new part of memory is allocated for fx jsfiddle.net/angkq8y7/1 Commented Dec 10, 2019 at 16:18

3 Answers 3

2

Since functions are passed by reference (like arrays), if you declare the function once, you can assign it to multiple objects, without duplicating it.

In your objectMaker the fx function is redefined whenever you call the function. Extract fx out of the objectMaker (define once), and assign it to each created object.

// define the function once
function fx() {
  return this.x += 1;
}

function objectMaker() {
  return {
    x: 0,
    fx
  }
}

var foo = objectMaker()
var bar = objectMaker()

console.log(foo.fx())
console.log(bar.fx())
console.log(foo.fx === bar.fx)

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

Comments

0

In Javascript, functions also are objects. If you define a function inside another function's brackets, Javascript will create a new function every time the outer function was called. If you want the function will be defined once, define it globally.

1. define a function inside other function

2. define a function globally

Comments

0

Every call to objectMaker you are recreating the fx function. Move it outside to global scope so only one instance is created

1 Comment

function re-use has been allowed by the spec since v3.

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.