Why javascript function has instance per call? - javascript

The javascript introduction says:
When I have code like below:
var Person=function(name){
this.name=name;
this.sayHello=function(){return 'Hello '+name;}
}
Whenever I instantiate a "Person", there will be a copy of "sayHello" function in the memory. To reduce this memory consumption, I can change the code like below:
var Person=(function(){
var sayHello=function(){return 'Hello '+name}
return function(name){
this.name=name
this.sayHello=sayHello
}
})()
In this way, there'll not be multiple copies of sayHello()
My questions are:
For the 1st type of code, what's the benefit except wasting more memory?
Should we write code in the 2nd way, or javascript should avoid one copy for one function per instance?
Thanks a lot.

The behavior you are witnessing is the result of two things:
Functions as first-class objects. This means functions are treated the same way as strings, numbers, arrays etc.
How local variables are treated in functions. Local variables are created (typically on the stack) each time the function is called. This allows functions to be called recursively.
This behavior exists in many different languages that have anonymous functions like Go, Perl, Lisp etc.
The two rules above means that each time you call your function the inner function gets created and assigned to the variable.
What's the advantage of this?
The primary advantage of this from the language point of view is consistency of behavior. It means functions are really treated as first-class objects just like numbers, strings etc. Treating it consistently means that people who try to use anonymous functions won't get surprised by the behavior.
How do people use this feature?
Sometimes you find yourself writing several different functions that look similar:
function double (x) {return x * 2};
function quadruple (x) {return x * 4};
Wouldn't it be nice to be able to categorize a "family" of functions that are similar and somehow write them once?
Well, in languages like C you may use a macro system to basically cut-and-paste the text you type to generate several different code.
In languages with first-class-functions you write a function to generate functions:
function makeMultiplier (factor) {
return function (x) { return x * factor }
}
So now you can do:
var double = makeMultiplier(2);
var quadruple = makeMultiplier(4);
Now OBVIOUSLY for this to work the makeMultiplier() function MUST return two different functions. It cannot just modify a single function to do different things each time it is called. Otherwise both the double() and quadruple() functions will multiply by 4 after the second call to makeMultiplier().
Implementation detail
It is possible to create a system whereby the body of inner functions are compiled only once and the differences are captured by a closure. So all functions only occupy RAM once but different versions of a function may occupy more than one closure. It is possible that this is how it's implemented by most js engines but I don't really know. If so, then inner functions do take up additional RAM each time they're defined but not by much (typically by one stack frame - so each function definition takes up the same space as a function call).
From the programmer's point of view though, inner functions must appear to work as if they're created each call because that's how you'd expect them to work.

For the 1st type of code, what's the benefit except wasting more memory?
The only time i'd use something like this is for quick testing of an anonymous object. An example of this would be in some sort of factory implementation:
getWidget = function(){
return {
foo: 'bar',
test: function(){ ... }
}
}
And honestly, this would be quickly replaced with proper coding conventions after I confirmed my initial testing.
Should we write code in the 2nd way, or javascript should avoid one copy for one function per instance?
I'd say no. Don't write code like this. It's unnecessarily convoluted and doesn't appear to work from what I can tell. I'd recommend just creating methods on the function prototype:
var Person = function(name){
this.name = name;
}
Person.prototype.sayHello = function(){
return 'Hello ' + this.name;
}
pros
- easy to read
- easy to manage
- this is scoped properly within the context of calling methods
cons
- a nominal increase in effort to code
- per a comment to the question, you lose access to variables scoped exclusively to the constructor

For the 1st type of code, what's the benefit except wasting more memory?
This could be used for access control (like private in some other languages).
Consider:
var Person=function(name){
this.sayHello = function(){return 'Hello '+name;}
};
name can only be accessed by sayHello, which is a opaque Function.
Other code may replace this.sayHello, but will not be able to let this sayHello instance use another name.

Related

How is the built-in Function object approach uses substantially more memory than the function literal?

Below snippet defines a function Robot() that is used as an object constructor—a function that creates an object.
function Robot(robotName) {
this.name = robotName;
this.sayHi = function () { console.log("Hi my name is "+this.name); };
this.sayBye = function () { console.log("Bye!"); };
this.sayAnything = function (msg) { console.log(this.name+" says "+msg); };
}
The second approach is
function Robot(robotName) {
this.name = robotName;
this.sayHi = new Function ("console.log('Hi my name is '+this.name); ");
this.sayBye = new Function ("console.log('Bye!'); ");
this.sayAnything = new Function("msg","console.log(this.name+' says '+msg);" );
}
The book which I am reading says -
The only downside to 2nd approach is that it will use substantially
more memory, as new function objects are created every time you create
a new instance of the Robot object.
I see when I do like below-
var wally = new Robot("Wally");
In both the approaches, wally robot has 3 function objects.
wally.sayHi(); //1
wally.sayAnything("I don't know what to say"); //2
wally.sayBye(); //3
How is the 2nd approach uses substantially more memory then?
When code gets parsed it'll be turned into an internal representation that the engine is able to execute. Now for regular code that happens once when the code is loaded. If you dynamically turn strings into code (as with Function) that happens when Function() is called, so each time your constructor gets called. Therefore using the second approach the engine has to create & keep another internal representation of the code, so if you create 10.000 instances, there will have to be 10.000 code representations. Additionally, this will not only eat up memory, it will also degrade performance, as optimizations are done on a per function basis, and the parsing of code also takes time, so the second approach will probably execute much much slower (yes, the engine could optimize those differences away, but I guess it probably won't).
There are a few other downsides:
1) No syntax highlighting from your IDE
2) unreadable code
So never, never, never ever use the second version. And get a new book as:
1) It makes no sense to learn how to dynamically create functions from strings, you will never have to use it.
2) It says that the second is worse because "new function objects are created every time you create a new instance of the Robot object", which applies to both the first and the second snippet (so thats not really a reason).
it's more about how javascript works.
As you know, on first launch, javascript create AST, and optimises code. So, in first case, function will be "precompiled" once. In second, AST and "precompilation" will be done every time
Most engines will create a new stack frame (more memory) as it has to invoke the interpreter for each new Function("") call, with an an anonymous IIFE (harder to debug) . It's similar to using eval(). Besides the memory issues, it allows for injection attacks and can also cause scope issues depending on strict mode.

JavaScript functions best practices

I'm brand new to JavaScript and currently learning about writing functions shorthand. I just came across this while studying:
const groceries = (groceryItem) => ' - ' + groceryItem;
Is it acceptable/best practice in the real world to write functions like this? (no return, no brackets) I notice that it may be annoying to expand upon. Or is this just standard practice?
I also notice shorthand if statements that have no brackets as well. Also standard practice?
I want to learn good habits early on, so any advice on this matter would be greatly appreciated.
There are several ways to declare functions and there are use cases and pros and cons to each. As a result, there is no "preferred" way. Use the appropriate syntax for your situation.
Below is a summary of the different ways to set up functions with a brief explanation of each. Click on the heading link to be directed to more in-depth resources on that type:
Function Declaration:
function foo(){
}
With a function declaration, the entire function is hoisted (regardless of it's actual location in the code) to the top of the enclosing scope. This makes it possible to invoke the function prior to its declaration point.
Function Expression:
var foo = function(){
}
Function expressions are just variable declarations that assign a function (as data) to the variable. As with function declarations, there is hoisting here too, but only the variable (foo in this example) declaration gets hoisted, not the assignment, so in this case you could not invoke the function prior to its declaration.
Arrow Functions:
const groceries = (groceryItem) => ' - ' + groceryItem;
This is simply a short hand syntax instead of using a function expression. However, there is a difference with an arrow function. With Arrow Functions, the object that this binds to is not affected within the function, while it is affected in a non-arrow function.
Immediately Invoked Function Expression:
(function(){
})();
An Immediately Invoked Function Expression (IIFE) is an anonymous function (a function with no name) that is turned into an expression by wrapping it with parenthesis and then immediately invoked with another set of parenthesis. This syntax is very common in JavaScript and is used to create a scope that doesn't conflict with other scopes.
NOTE:
Functions are the work horses of JavaScript, depending on how you set them up and invoke them, they do many different things:
They can be units of directly invocable code.
They can be the value of a variable or property.
They can be constructor functions that are used to instantiate Object
instances.
They can be raw data that is passed around via arguments.
Yes, I think this is considered acceptable, since arrow functions were specifically designed to allow it. One of the features of arrow functions is that they allow very simple functions to be written as one-liners like this. When you can calculate the return value as a single expression, you don't need to write the body with braces around it or the return statement explicitly. This makes traditional functions needlessly verbose, with more boilerplate than the actual code of the function. The traditional alternative would look like:
const groceries = function(groceryItem) {
return ' - ' + groceryItem;
}
This isn't so bad when defining a named function, but when you're using an anonymous function as a callback, all that verbosity may obscure the intent. Compare:
newarray = oldarray.map(function(x) {
return x * x;
}
with:
newarray = oldarray.map(x => x * x);
Arrow functions are a recent addition to the language, so I think we can assume that the design was given significant consideration. If the Javascript community didn't feel that shorthand functions like this were a good idea, they wouldn't have been allowed in the first place.
The function you wrote is what is commonly known as a "arrow function". They can prove very useful when you get to a somehow more advanced level in JavaScript and there is absolutely nothing wrong with them. On the contrary. Very commonly used with "higher order functions" for arrays, to give an example.

Specific real life application of closures in javascript

I have used JS for two years and my pluralsight accessment rates me as proficient in JS, I understand prototypical inheritance, higher order functions, IIFEs etc and I have used them in real world instances but closures is one of those concept that you understand but can't find any reason why you would want to use them in real world development, I mean I know that if I say,
function expClosure(val){
//do something to val-->anotherVal
return function(val){return anotherVal)};
}
var exp = expClosure(val);
exp(); --> returns the value of anotherVal;
My question is why would I want to do this, or rather what specific instances can lead me to consider using this.
The main benefit to closures is you can "partially apply" a function using a closure, then pass the partially applied function around, instead of needing to pass the non-applied function, and any data you'll need to call it (very useful, in many scenarios).
Say you have a function f that will need in the future 2 pieces of data to operate. One approach is you could pass both pieces in as arguments when you call it. The problem with this approach is if the first piece of data is available immediately, and the second isn't, you'll have to pass it around with f so it's in scope when you want to call the function.
The other option is to give the available data to the function immediately. You can create a closure over the data, have the function reference the external data, then pass the function around by itself.
Option 2 is much simpler.
You can also use closures to implement static variables in functions in languages that don't natively support them. Clojure (the language) implements it's memoize function by having it return a modified version of the passed function that holds a reference to a map representing argument/return value pairs. Before the function is run, it first checks if the arguments already exist in the map. If they do, it returns the cached return value instead of recalculating it.
(Adapted from my answer to another question)
I wrote a bit about this in my practical bachelor thesis(2.2.2)
Hiding variables is a valuable usage of closure. Compared to some other languages variables can't be declared as private, public, etc. in JavaScript, but using closure you can hide variables that can only be used internally. E.g.
function Car() {
var speed = 0;
return {
accelerate: function() {
speed++;
}
}
}
var car = new Car();
car.accelerate();
speed is accessible by accelerate due to closure, but is otherwise completely inaccessible.
Since this question doesn't demand a programmatic answer, I am adding an answer and not a comment.
The example you quoted in the question is, I agree of a closure, and I am sure having access to pluralsight lectures, you well understand closures. So the aforestated example is not the only use case of closures. The closures are the functions which remember the scope in which they were created.
An obvious example of this is a callback registering mechanism which every one uses in jQuery. There are closures everywhere, and many of us have been unknowingly writing closures.
So if you have used redux, you would know the entire concept is based on closure, i.e. encapsulating the data(called state of application). Closure provisions a concept of private variables used in OOPS supporting languages.
I am adding another example of closure below, so you might be able to relate.
function processOrder(amount){
var temp_order_id = +new Date() + 'USERID';
var afterPaymentCompleteOrder = function(status){//callback
//afterPaymentCompleteOrder is a closure as it remembers the scope in which it is created when it is being called. So when ivoked it remembers the value of temp_order_id
if(status){
complete_order_method(temp_order_id);
}
else
delete_order_details(temp_order_id);
}
start_payment_process(amount, afterPaymentCompleteOrder);
}

What are the benefits of writing "functional" Javascript as opposed to OO?

I often come across Javascript code snippets that consist of many anonymous functions that are called where they are created, such as here:
var prealloc = (function() {
// some definitions here
return function prealloc_win(file, size, perms, sparseOk) {
// function body
};
})();
// can be called like this:
prealloc(...);
So this calls an anonymous function which returns another function prealloc_win. To me this seems equivalent to instantiating a class where the resulting object exposes the function prealloc_win:
function preallocObj() {
// some definitions here
this.prealloc_win = function(file, size, perms, sparseOk) {
// function body
};
}
prealloc = new preallocObj();
// can be called like this:
prealloc.prealloc_win(...);
Is this assumption correct? What are the benefits of using anonymous functions that are called directly? And why is this idiom so often seen in Javascript, but not often in other languages which could be written in the same way (C, C++, Python)?
The deal is that the preallocObj class says that this is something that could be
instantiated multiple times. I could just create more instances of it even though it wasn't really designed for that. You could do some hacks to prevent that but it's easier just to use the immediately invoked anonymous function for this.
With the immediately created and invoked anonymous function, a "class" is created, instantly "instantiated" and assigned to prealloc and
there is no way to reference the original anonymous function that created the prealloc object after this. It was created, invoked and lost.
You pretty much have the right idea. The benefits of this module pattern/function builder are that the resultant function can enclose its own internal definitions or state.
It's basically just a way to create a function with private variables or constants. Consider the less efficient alternative:
var prealloc = function() {
// some definitions here
// function body
}
Every time this function is called it would reassign/instantiate its variables, adding unnecessary performance overhead and overwriting any state data that resulted from previous calls.
This method is useful when there are some variables that are important to the workings of a function that you want only private access to or that you need to persist between invocations without contaminating the outer scope.
Javascript is fundamentally very different to C++, JAVA and Python and should be written in differnt ways. At the risk of repetition, Javascript is not an OOP language it is a prototype language. Douglas Crockford (inventor of JSON) at Yahoo has some wonderful articles and particuarily Videos entitled 'Javascript - the good parts' you should watch them all.

Accessing variables from other functions without using global variables

I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function.
If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
To make a variable calculated in function A visible in function B, you have three choices:
make it a global,
make it an object property, or
pass it as a parameter when calling B from A.
If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
Consider using namespaces:
(function() {
var local_var = 'foo';
global_var = 'bar'; // this.global_var and window.global_var also work
function local_function() {}
global_function = function() {};
})();
Both local_function and global_function have access to all local and global variables.
Edit: Another common pattern:
var ns = (function() {
// local stuff
function foo() {}
function bar() {}
function baz() {} // this one stays invisible
// stuff visible in namespace object
return {
foo : foo,
bar : bar
};
})();
The returned properties can now be accessed via the namespace object, e.g. ns.foo, while still retaining access to local definitions.
What you're looking for is technically known as currying.
function getMyCallback(randomValue)
{
return function(otherParam)
{
return randomValue * otherParam //or whatever it is you are doing.
}
}
var myCallback = getMyCallBack(getRand())
alert(myCallBack(1));
alert(myCallBack(2));
The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo, then place the result into a fresh var and reference this new var within functionTwo. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
If another function needs to use a variable you pass it to the function as an argument.
Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
Another approach is one that I picked up from a Douglas Crockford forum post(http://bytes.com/topic/javascript/answers/512361-array-objects). Here it is...
Douglas Crockford wrote:
Jul 15 '06
"If you want to retrieve objects by id, then you should use an object, not an
array. Since functions are also objects, you could store the members in the
function itself."
function objFacility(id, name, adr, city, state, zip) {
return objFacility[id] = {
id: id,
name: name,
adr: adr,
city: city,
state: state,
zip: zip
}
}
objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);
"The object can be obtained with"
objFacility.wlevine
The objects properties are now accessable from within any other function.
I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call.
Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. To many actors fiddling with something can create chaos.
You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).
Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):
How to get a variable returned across multiple functions - Javascript/jQuery

Categories