How does the functions differ from objects in Javascript? [duplicate] - javascript

This question already has answers here:
Set document.getElementById to variable
(5 answers)
Closed 5 years ago.
I have this habit of using function id(_id) { return document.getElementById(_id); } as to lessen the work of typing this over and over.
sidenote:
jquery becomes too heavy for small tasks and projects
As I learnt Javascript more I came to know that we can pass around functions just like objects so we can do
var id = document.getElementById;
It seems like both do the exact same thing. However, I am not an expert in Javascript, so could there be any difference internally? and which is the preferred way of using?

Yes, the context is:
const log = console.log;
log("test");
The upper wont work because the context changed, and log must be called on a console object, not on window ( aka without context). However, there are easy workarounds:
const log = console.log.bind(console);
Or you use functions, for example the arrow ones:
const log = (...args) => console.log(...args);

Related

Is it possible to dynamically de-structure return? [duplicate]

This question already has answers here:
How to destructure into dynamically named variables in ES6?
(6 answers)
"Variable" variables in JavaScript
(9 answers)
Closed 1 year ago.
I understand this is a very dumb question, I am dumb, maybe confused.
Let us say that I have a module foo.js that after doing works returns an object like this bellow,
return {something, anotherThing, yetAnotherThing};
Now, I want to get those in my bar.js and work with, but not with all of them. Maybe sometimes with something and sometimes with anotherThing etc. So, what I do is,
const foo = require('../foo.js')
const { something } = foo()
Then I work with something in my files.
The problem here is, most of the time, I need something or anotherThing on a random basis. Like I do not know which one I will need. Sometimes I need all of them and somethings I need only one or two.
So, is it possible to write a function that dynamically gets the destructed variables and work with them? For example, if I create an array of the things needed from the foo file and pass that array to a function that takes element from the array to get variable from foo.js and work with it? An incorrect code example of what I am saying will be,
const iAmWrong = ( arr) => {
for (let i = 0; i < arr.length; i++) {
const { arr[i] } = foo();
}
arr[i]();
};
There must be a way to achieve this right? Maybe not how I am thinking it is in code but I hope it is not impossible.
Please help.

How to see the code of a javascript function? [duplicate]

This question already has answers here:
How can I read ‘native code’ JavaScript functions?
(3 answers)
Closed 3 years ago.
This may be a very dumb question.
I want to see the code of a function (Built in and User defined) in Javascript.
For example :
function hello(){
console.log("hello")
}
hello.toString() // Gives the function definition
'function hello(){\nconsole.log("hello")\n}'
Is there a way to see the native code like Math.random.toString()?
Update: From the comments, Seblor explained that native code cannot be seen.
You could do some string formatting to get a "better" look at your functions. Use this peace of code to get rid of the function name to get just the code.
function justGetCode(funcName)
{
var tempString = funcName.toString();
tempString = tempString.substring(tempString.indexOf("{"));
return tempString
}
But beyond this there is little you can do in terms of digging into native (i.e. browser specific ) code as it is encapsulated. This should work on library functions however.
Now i do not know what you are planning on doing with the returned function, but for fancier function manipulation you can always use in-built reflection mechanisms

Dynamically call function in javascript [duplicate]

This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();

Javascript. Swap two variables. How it works? [duplicate]

This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.

What is the point of prototypes in JavaScript? Why not add method directly to constructor? [duplicate]

This question already has answers here:
Declaring javascript object method in constructor function vs. in prototype [duplicate]
(3 answers)
Closed 9 years ago.
So I am going over a few lessons over JavaScript at CodeAcademy, and I ran into this section regarding prototypes.
A bit from the code:
function Dog(breed){
this.breed = breed;
};
Dog.prototype.bark = function(){
console.log("Bark!");
};
I don't understand the point of doing it that way. Why not just do it this way? (The way I first learned.)
function Dog(breed){
this.breed= breed;
this.bark = function(){
console.log("Bark!");
};
}
The second way, everything is together in one block, and not separated. What is the advantage of the first one? I know that there is, I'm just not seeing it.
One difference is, that in the prototype case the function exists only once and changing it will change all objects using this prototype. In the this. case the function is repeated in every object.
This makes a difference both in footprint and semantics.
it is for performance reasons. when creating a new instance of objects and calling a native method you are eating more memory for every creation.
On the other hand when using prototype it is more memory safe regardless the amount of Object created.

Categories

Resources