Trying to learn basic javascript, but ran into some issues.
Is it true that the following script stores the string to the parameter, turning it to a variable:
function funcOne(paraOne) {
document.write(paraOne);
}
funcOne("A Message");
Am I understanding it correctly, that this is equivalent to var paraOne = "A Message"; ?
Because when I try using this variable elsewhere, an error message just shows in console saying:
ReferenceError: Can't find variable: paraOne
Wondering what I am missing here.
The scope of a parameter is limited to the function that defines it. So, for example, this would be perfectly legal:
function funcOne(paraOne) {
document.write(paraOne);
console.log(paraOne);
}
funcOne("A Message");
While this would cause a RefernceError:
function funcOne(paraOne) {
document.write(paraOne);
}
funcOne("A Message");
console.log(paraOne); // Error here!
Related
So I'm creating a mod for the singleplayer browser game Cookie Clicker. In my mod I allow the user to insert in their own code to do their own special things to interact with my mod's main function.
However, when the user codes on my custom editor, I want to "test" their code before they save to make sure no errors happen, and if they do, display a error message with what they did and where they did it. Getting the error is easy with a try/catch. But I noticed the error message is:
SynaxError: missing ) after argument list
at new Function (<anonymous>)
at HTMLAnchorElement.save.onclick (chrome-extension://dhdgffkkebhmkfjojejmpbldmpobfkfo/userscript.html?name=Building%2520Sorter.user.js&id=18320655-b018-42e2-8fa5-7fb0cc8d2d70:578:24)
Which isn't helpful for me at all. The most I could salvage from this is the first line. However, that doesn't tell the user at all where the error is located in their code.
the 578:24 that points to the supposed error is:
try{
//code.value is a STRING of the user's code
let func = new Function(code.value);//<-- error points here in my source code.
func.call(null, [[0, 1, 2], Game]);
save.classList.remove('ModBuildingSorter_unsaved');
}
catch(e){
console.dir(e);
}
What I would like to happen is when the user sumbits:
return function(array){
return array.sort(function(building1,building2){
return building1.price - building2.price;
};// missing array.sort closing parenthesis
}
get's ran, I can get a syntax error telling me it's on line 4
Is there a way I can do this? Make the user's code act kinda like it's own file and try running it so I can find out which row & column the error is located?
You could, in theory, run the function from an eval()
i.e.:
try {
let a = "function test(o){console.lo(o)}test('hello');" // Minified function
eval(a)
} catch (e) {
console.log(e)
}
Here is the unminified function for example purposes:
function test(o)
{
console.lo(o) // <-- Error
}
test('hello');
and this returns the error correctly, which is
TypeError: console.lo is not a function
at test (eval at <anonymous> (D:\StackOverflowSandbox\index.js:3:5), <anonymous>:1:26)
Hope I've helped.
var test = function(msg) {
alert(msg)
};
(new test("hi")).run();
(new test("hello")).run();
When I run above javascript code, I am able to get alert "hi". But alert "hello" is not coming up.
Anybody can explain what is above, I am completely new to this. Only I know is that "test" is a function
What is run() method does?, because when I removed run in the above code, I am able to see both alerts, pls help...
var test = function(msg) {
alert(msg)
};
(new test("hi"));
(new test("hello"));
Simple, there is no run function, when your code runs (new test("hi")).run() it runs the (new test("hi")) part first, and then errors on the run so the second line is never executed.
If you want to call a function, call it:
test("hi");
Don't run functions (that are not constructors) as constructors. Here is what new does.
"run" is not a defined function.
Even if you replace "run" by "xyz"|| "abc" or any other random function name which is not defined, the code above will work in the same way.
var test = function(msg) {
alert(msg)
};
/** test("hi") getting called, then xyz() throws a javascript error **/
(new test("hi")).xyz();
/** No Execution as there was an error on previous line **/
(new test("hello")).xyz();
Its's just that initially the "test" function is called once and when it encounters a .run() which is not defined, it throws an error and execution stops.
Couldn't you use a find & Replace routine to read the cookie and then replace it with ''?
I have not been able to delete all path cookies using all of the tips above and am still playing with it, but I did make a bookmarklet to extract all the cookies and put them in an iframe so that you can copy&paste them.
javascript: var c=document.cookie;if (c==''){alert('This site didn\'t give you any cookies at all.\nNot a single one!');}else{w=window.open('','Links','scrollbars,resizable,width=400,height=600');w.document.write(c); }
Though Stackexchange Meta forbids me to start with "Hi,", I think there is no substantial harm to being friendly.
Hi,
I use the following piece of code,
while (!success) {
new Magister(chosenSchool, username, password).ready(function(error){
/* Code here using the error variable above */
});
}
but JSLint warnes me that it would be a bad practice to define functions inside a loop.
However, using the following code, doesn't work either.
function checkLogin(error) {
/* Code here using the error variable above */
}
while (!success) {
new Magister(chosenSchool, username, password).ready(checkLogin(error));
}
This results into Uncaught ReferenceError: error is not defined. How can I not redefine a function, but still passing the error as in the original function(error){...}?
I tried various methods, but it won't budge for me.
Thanks in advance!
Just don't call the function:
new Magister(chosenSchool, username, password).ready(checkLogin);
ready expects a function object, so you have to pass chechLogin itself instead of calling it and passing its return value (which is likely undefined).
How can I not redefine a function, but still passing the error as in the original function(error){...} ?
Maybe that's where the confusion lies. You are actually not passing error at all. The argument is passed by the caller, which is ready.
One nice feature of JavaScript is that you can simple replace variables with the literal representation of their value (in most cases).
So if we look at
new Magister(...).ready(checkLogin(error));
and replace checkLogin with it's value (the function) it becomes
new Magister(...).ready(function checkLogin(error){...}(error));
However, that doesn't look like the first version at all! Suddenly a wild (error) appears at the end of our function definition.
Lets go the other way round:
new Magister(...).ready(function(error){...});
// becomes
new Magister(...).ready(function checkError(error){...});
// becomes
function checkError(error) { ... }
new Magister(...).ready(checkError);
Much better.
I'm actually new to JavaScript as well as Jasmine. So it might be something really obvious that fixes my problem but I can't see it.
I want to check if (an already existing) JavaScript application calls console.error() while loading. I don't really see a way how to realise this with Jasmine. I've included the JavaScript file as well as the spec file in the SpecRunner.html.
But I take it that I somehow need to "instantiate" the application in order to test if it throws any errors on the console, right?
Or should I include the SpecRunner.html code only for this purpose into the HTML code of the app?
You can spy on console.error like this:
beforeEach(function(){
spyOn(console, 'error');
})
it('should print error to console', function(){
yourApp.start();
expect(console.error).toHaveBeenCalled();
})
You can override the standard console.error function like this:
//call the error function before it is overriden
console.error( 'foo' );
//override the error function (the immediate call function pattern is used for data hiding)
console.error = (function () {
//save a reference to the original error function.
var originalConsole = console.error;
//this is the function that will be used instead of the error function
function myError () {
alert( 'Error is called. ' );
//the arguments array contains the arguments that was used when console.error() was called
originalConsole.apply( this, arguments );
}
//return the function which will be assigned to console.error
return myError;
})();
//now the alert will be shown in addition to the normal functionality of the error function
console.error( 'bar' );
This solution works with Jasmin or anything else. Just put the code above before the other codes and any call after this to console.error() will call the overridden function.
use toThow and toThrowError http://jasmine.github.io/edge/introduction#section-Spies:_and.throwError
I have a very odd problem that I have to assume is because of Yabble.js. I have never used Yabble.js before, and the only reason I am now is because it is a dependency of a library I'm using (Gamejs), but I would love to understand why this happens, and whether it is actually Yabble.js's fault, or possibly Gamejs's.
Here's a heavily compressed (and modified for genericness) version of my main.js:
var gamejs = require('gamejs');
...
function Character(/*lots of arguments*/) {
Character.superConstructor.apply(this, arguments);
this.somethingtomakeitaprototypeforthisexample = oneofthearguments;
}
gamejs.utils.objects.extend(Character, gamejs.sprite.Sprite);
Character.prototype.draw = function(display){
display.blit(this.animator.image, this.pos);
}
... /*Skipping most of the file, irrelevant to the problem*/
function main() {
maincharacter = new Character(/* appropriate number and types of arguments */);
... /*skipping the rest*/
}
gamejs.ready(main);
I have done enough debugging to know that it gets into the main function no problem and that the break occurs at the call to Character. Here is the error message (from Chrome's console):
Uncaught TypeError: undefined is not a function
main
_readyResources
I have determined that Character is the undefined function. However, if I define my ready function thusly:
gamejs.ready(function(){
console.log('Character:');
console.log(Character);
main();
});
the full contents of Character, as properly defined, prints out, but I still get the error in main. Thus, I know that Character is defined by the namespace before main is called.
Fun fact though: I do have a workaround. If I change the function prototype for main to:
function main(CharacterClass) {...};
then change the ready function to:
gamejs.ready(function(){ main(Character); });
and change the relevant line in main to:
var character = new CharacterClass(...);
it works fine. But this feels really hackish.
So my question is not how to make it work, since I have that already, but rather why it is a problem and how to make it work like it's supposed to.
Any thoughts?