Javascript: Function overwrite with passing arguments [duplicate] - javascript

This question already has answers here:
Passing arguments forward to another javascript function
(5 answers)
Closed 8 years ago.
I am using Winston (Logger for nodejs).
In my script i call:
log.error("my error", {input: [1,2]});
console show me:
error: my error input=[1, 2]
What i want to do: don' call at log.error(null)
In some functions i dynamically call the log.error with a variable and dont know if the variable are NULL or have a value. If i call log.error(null) he write "error:" to the console.
I tried with this:
log.error = (function () {
var old = log.error;
return function newerror() {
if (arguments.length !== 0) {
old(arguments);
}
};
})();
But now i got:
error: 0=my error, input=[1, 2]
as output.
My Question
how i can call the log.error() function with die arguments given (arguments-var in javascript is a object).
Function style:
function foo(arg1,arg2,...)
I want something like:
foo.call(myargumentsobj);

oh i got it:
old.apply(this, arguments);

Related

How does this javascript class and method work? [duplicate]

This question already has answers here:
Where do the parameters in a javascript callback function come from?
(3 answers)
Closed 4 years ago.
As seen here from Twilio's documentation, how does the following code work? We have a connection class and an on method. If I haven't previously defined what hasEarlyMedia, showRingingIndicator, or playOutgoingRinging mean, then how does the on method know what they mean and what to do with them? Thanks.
connection.on('ringing', function(hasEarlyMedia) {
showRingingIndicator();
if (hasEarlyMedia) { playOutgoingRinging(); }
});
Maybe is easier to understand if we rewrite the code like this:
// when the Connection has entered the ringing state,
// call handleRingingEvent (callback function) and pass an argument,
// a boolean denoting whether there is early media available from the callee
connection.on('ringing', handleRingingEvent);
function handleRingingEvent(hasEarlyMedia) {
showRingingIndicator();
if (hasEarlyMedia) {
playOutgoingRinging();
}
}
// if not defined somewhere else
function showRingingIndicator() {
// do something
}
// if not defined somewhere else
function playOutgoingRinging() {
// do something
}
I hope this helps.
hasEarlyMedia is an argument. Please check
showRingingIndicator(); and playOutgoingRinging(); method must be defined somewhere. Must be function declared in your one of the library which you have included in your file.

`onStartedProcess` callback never get called [duplicate]

This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 4 years ago.
I bind a function with this code
this.process[id].on('started', this.onStartedProcess.bind(this)); // I want to pass an extra variable here.
Then, in the process, when I call this code
that.emit('started', {startTime:time, instance: that});
The following function is called
onStartedProcess(info) {
console.log(info.startTime);
}
Is it possible to pass an extra variable to the onStartedProcess function when biding it? Something like
this.process[id].on('started', this.onStartedProcess.bind(this,otherParameter));
and use the parameter when the onStartedProcess is called because of the emit, for example
onStartedProcess(info, otherParameter) {
console.log(info.startTime);
console.log(otherParameter);
}
I red this post about the bind method but still can't find a way to achieve what I want to do.
Edit:
This is not working for me. This is what I tried
this.process[id].on('started', this.onStartedProcess.bind(this, 5));
that.emit('started', {startTime:time, instance: that});
onStartedProcess(info, otherParameter) {
console.log(otherParameter); // I was expecting the get the 5 here
}
onStartedProcess never get called
Yes. You are describing how bind function works. First pass the context (this), then all additional parameters you need.
Read the docs here
The problem is with the arguments order in the function you are binding.
onStartedProcess(info, otherParameter) {
// with your current `.onStartedProcess.bind(this, 5)
// you are binding `info` argument to `5`
console.log(otherParameter); // I was expecting the get the 5 here
}
If you want to currently set otherParameter to 5 you need to properly bind the second argument: .bind(thisArg, firstArg, SecondArg)
Regarding to the callback not being called.
This is one solution for your scenario:
// parent.js
const { fork } = require('child_process');
const subprocess = fork('child.js');
subprocess.send('start');
subprocess.send({ hello: 'world' });
// child.js
process.on('message', onStartedProcess.bind(null, 'first arg', 5));
function onStartedProcess(info, otherParameter, message) {
console.info('callback args:', info, otherParameter, message);
}
Running node parent.js you should get this output:
callback args: first arg 5 start
callback args: first arg 5 { hello: 'world' }
Read more about node process messaging here

Unexpected Uncaught TypeError [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This code is an external file, test.js, which is linked to from index.html, after the jQuery file.
When I refresh my browser and go into the console, I get this error message:
Uncaught TypeError: Cannot read property 'starshipName' of undefined
on line 20, where I try to alert the starshipName property of the first item in the array.
var starships = [];
function starship(starshipName, model, manufacturer) {
this.starshipName = starshipName;
this.model = model;
this.manufacturer = manufacturer;
}
function starshipData(data) {
for (i = 0; i < data.results.length; i++) {
var results = data.results[i];
starships.push(new starship(results["name"], results["model"], results["manufacturer"]));
}
}
$.getJSON('https://swapi.co/api/starships/', function(data) {
starshipData(data);
});
alert(starships[0].starshipName);
However, when I type out the last line of code or log the starships array to the console, it works perfectly. I am very confused as to why this is happening and will appreciate any help! Thank you in advance.
$.getJSON is an asynchronous function. This means that your alert() is called before starships is filled with data - hence the undefined property error.
All operations that depend on an async function must be placed in, or called from, the callback. Try this:
$.getJSON('https://swapi.co/api/starships/', function(data) {
starshipData(data);
// 1: place the call in the callback
// 2: always use console.log to debug as it does not coerce data types
console.log(starships[0].starshipName);
});

PhantomJS: call a user defined/custom function within phantomjs [duplicate]

This question already has an answer here:
Cannot pass module functions to Page
(1 answer)
Closed 6 years ago.
i'm getting a ReferenceError when i call a function i defined myself inside the page.evaluate() of Phantom; what is the proper way to do that ?
for example:
function mySweetFunction(item) {
// process item....
}
page.evaluate(function(){
var item= document.getElementsById('item');
mySweetFunction(item);
});
then i'll get the error:
ReferenceError: Can't find variable: mySweetFunction
What is the proper way to do this ?
mySweetFunction is quite big, and i would prefer to keep it out of page.evaluate(...) if possible.
If you want to use a function inside page.evaluate() you have to put it there first:
page.evaluate(function(){
function mySweetFunction(item) {
// process item....
}
var item = document.getElementsById('item');
mySweetFunction(item);
});

How to know when a JavaScript function is called from a console? [duplicate]

This question already has answers here:
How can we know if a function is called from console or from source code
(3 answers)
Closed 7 years ago.
I want a particular JavaScript function to behave differently depending on if it's called within JavaScript code referenced from an HTML page or called from within a console. Is this possible? Something like the following:
function mySpecialFunc() {
if (inConsole())
console.log("You called me from the console!");
else
console.log("You called me from an HTML page or a JavaScript file linked from an HTML page, I think.");
}
Does something equivalent to the inConsole() function above exist?
Does this exist for at least just Chrome specifically, or Firefox specifically?
One way is to throw an error and check the stack trace for a string that is unique to the console's injection. Something like "InjectedScript"
Here is an example that works.
var f = function(){
var injected;
try {
throw new Error();
} catch (e) {
injected = e.stack.match('InjectedScript');
}
if (injected) {
console.log("Called from console");
} else {
console.log("Called from code");
}
}
// Add it to window so we can call it from the console.
window.f = f;
f();
Unfortunately there is no way to tell via system input, but you can do it "Manually" in a sense using overflow/overload functions. See here for a excellent tutorial on how to use overflow/overload in js.
So in your code that calls the function in javascript add an additional argument to the call that will tell the function it is not called from the console.
mySpecialFunc() <---- From console
mySpecialFunc(value) <---- From code

Categories

Resources