Method to call a function in javascript in a particular way [duplicate] - javascript

This question already has answers here:
How do I write an extension method in JavaScript?
(2 answers)
Add method to string class
(6 answers)
Closed 2 years ago.
I am kinda new to js and would appreciate some help to clarify one subject.
Basically i want to call some functions that i write like default javascript are called:
//declaring function
const splitAsExample = text => text.split('|')
//calling function
splitAsExample('Yesterday|Today|Tomorrow')
Instead of calling the function as mentioned above, i would like to know if it's possible to make a function that can be called like:
'Yesterday|Today|Tomorrow'.splitAsExample()
//and || or
'Yesterday|Today|Tomorrow'.splitAsExample
I learned js all by myself and didn't manage to find a specific name for this question to search up in google. :)
If you can clarify this topic for me it would be great, but if you could give me the name to search it up would be even better!

You could add a prototype function to String.
This allows method chaining with a given object.
String.prototype.splitAsExample = function () { return this.split('|'); };
console.log('Yesterday|Today|Tomorrow'.splitAsExample());

Related

Unable to add property to object using method with this keyword [duplicate]

This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 5 months ago.
I'm trying to add a property to an object using a method. Here is the code:
const siddhu = {
name: 'Siddhu',
friends: ['Dylan', 'Jordans', 'Aathi'],
setBestFriend: () => this.bestFriend = this.friends[0],
setNumOfFriends: () => this.numOfFriends = this.friends.length,
}
siddhu.setBestFriend()
siddhu.setNumOfFriends()
console.log(`${siddhu.name} has ${siddhu.numOfFriends} friends, and his best friend is ${siddhu.bestFriend}`);
For some reason, this doesn't work. I know that changing the this keyword to siddhu fixes the problem, but this isn't ideal, as I want to be able to copy-paste this code multiple times, and I would have to change siddhu every time I did.
No problem - apparently you can't use this with arrow functions because then this would reference the arrow function. All credit goes to jonrsharpe for telling me!

Javascript const arrow function [duplicate]

This question already has answers here:
How do I call a JavaScript function on page load?
(8 answers)
why don't const and let statements get defined on the window object [duplicate]
(2 answers)
Closed 2 years ago.
I know is kind of a dumb question but I'm kinda confused, tried to look up on the internet but couldn't find anything so..
when in JS (ES6) I declare an arrow function as const, how can I invoke it when page is loaded?
es.
const bigBla = async () => { bla bla };
tried smt like onload="bigBla()" but doesn't work, also tried to invoke it at the end of the JS file but won't work in the HTML file (need to change innerHTML of a span element/src of an iframe, data come from http request), whereas if i declare function bigBla(){...} and use onload="bigBla()" i have no problems. Help me :(
Try window.onload function in your javascript file.
window.onload = function() {
bigBla();
};

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: Why name object method functions [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 6 years ago.
In some projects I can see, that the functions wich are object methods get names after the function constructor - I can not see why, can any one explain?
Example: named
someObj.prototype = {
load: function someObj_load(file) {
vs unnamed
someObj.prototype = {
load: function(file) {
I can not see any advantage in the above.
So you can see the name of the function name instead of Anonymous function in stack traces. I think some browsers will pick up the name of the variable/attribute you've assigned it to. Some don't.

Categories

Resources