Is A Function Stored In Memory Only Once?
Solution 1:
If you define the function one time, and pass a reference of that function to different variables/properties, then yes, it's stored one time.
var one_func = function () { console.log("I'm just one function."); };
var reused = one_func;
var reuser = { func : reused };
All of them have pointers to the same function.
But if you have something like this:
varCircle = function (r) {
var circle = {
radius : r,
calculate_area : function () { return2 * Math.PI * r; }
};
return circle;
};
var circle_1 = Circle(2),
circle_2 = Circle(4);
The two objects do NOT share calculate_area
.
You've created two distinct versions of the function.
And they must remain distinct due to function-scope and closures.
See, each copy knows about its own circle's r
.
If you notice, I'm not looking at circle.radius, I'm looking at the r
passed into the Circle
function.
So any function which is defined inside of Circle
has to be new every single time, because those functions save references to any variables inside of the constructor, through closure.
The memory-hit of having multiple copies, versus the benefits of having totally private properties is well worth it, until you hit thousands and thousands of copies (unless we're talking about gigantic objects or horrible old browsers, or running JavaScript on an LED screen on a Toaster).
More advanced engines might optimize the memory-footprint here, but it's rarely worth wasting the CPU, given how little memory each of these functions would take up, and how much RAM smartphones have (let alone custom-built gaming PCs).
EDITfor the sake of pedantry
varWallet = function (opening_balance) {
var balance = opening_balance,
overdraft = 50,
is_sufficient_funds = function (amount) {
return balance + overdraft >= amount;
},
deposit = function (funds) {
if (amount <= 0) { return; }
balance += funds;
},
withdraw = function (amount) {
if (amount <= 0) { return; }
if (is_sufficient_funds(amount)) {
balance -= amount;
return amount;
}
},
public_interface = {
deposit : deposit,
withdraw : withdraw
};
return public_interface;
};
Now, it should be blisteringly-apparent that we do not want balance
or overdraft
to be publicly accessible in any instance of Wallet
.
Even this pedestrian version of Wallet is quite safe.
Sure, it's not doing any authorization right now, so you can deduct everything, or add a million dollars...
...but can you set your overdraft to $300?
Can you manually copy the value of balance
?
Even if you created var wallet = Wallet(35);
and then tried to rewrite the deposit
method, your rewriting of it would then have absolutely no access to the private balance
.
Now the closure-related benefits of this memory-overhead should be apparent.
If you'd prefer, you could consider the rate of fire of a gun in a multiplayer game. Or a character's movement. Or their health. Or high-scores.
By keeping all of these things encapsulated in closures, they're untweakable. That doesn't mean that the server is unhackable. But it does mean that there's one less spot for people to get in, without rewriting your engine from the ground up.
Solution 2:
It's kind of hard to tell what you're asking, but I see two possible questions and therefore two answers:
A JavaScript function is created once for each execution of the execution context in which you've defined it. So if that context is global (outside of any function), yes, each declaration or expression will create only one function. If that context is within a function, they'll be defined each time the function is called.
So for example, if this is a global scope:
function foo() { }
...only one of those will be created. In contrast, something like this:
functionbar() { return { foo: function() { } }; }
...creates a new function and assigns it to the
foo
property on the returned object each timebar
is called. (That doesn't mean a smart JavaScript engine can't share the underlying code for them — and I'm told by people who claim to know that V8 [the engine in Chrome and elsewhere] does indeed reuse the code — but they'll be separate function objects.)Each function declaration or expression creates its own function; if you have two equivalent declarations or expressions, they create two functions, even though they're equivalent. That doesn't mean that a smart JavaScript engine can't share the underlying code under-the-covers, but you'll still have two separate function objects.
So for example:
var a = function() { }; var b = function() { }; console.log(a === b); // "false"// Adding a property to `a`, since functions are objects, demonstrates// further that they are not the same function object a.foo = "bar"; console.log(a.foo); // "bar"console.log(b.foo); // "undefined"
Solution 3:
No. The anonymous function
function(){
alert("some value");
}
is not the same as the anonymous function inside the object literal obj
.
To make sure you 'recycle' a stored object or function, do somethign like this:
var f = function(){ alert('test') };
obj = {
m: f
}
Post a Comment for "Is A Function Stored In Memory Only Once?"