Weird Object Error in Javascript - javascript

First, I'm not a javascript developer so I don't have a great deal of experience in this if any.
I have a footer I'm inserting into an HTML page using jQuery that has the following code in it that per the client "NEEDS TO BE THERE".
<script language="JavaScript"><!--
/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code=s.t();if(s_code)document.write(s_code)//--></script>
<script language="JavaScript"><!--
if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')
//--></script>
I don;t really have to worry about anything except this s.t(); line of code. I need to write a dummy Object or whatever else and include it in the header that doesn't do anything per se except prevent a javascript error from occurring.
So really I need "s" the object to be instantiated and have a function "t" attached to it that basically does nothing.
Any help is appreciated. This isn't something I want to do but given the budget and project constraints of the client I just need for this to work without a javascritp error.
thanks if you can help.

Using javascript prototype:
function s () {
}
function doSomething () {
}
s.prototype.t = doSomething;
edit: typo

var s = {
t: function(){}
};
See it in, hmm, action: http://jsbin.com/oboju
In case you're worried s is defined and don't want to override it, you can check for it first (this doesn't cover the case s.t is defined but isn't a function):
if(!s){ // check if s exists
var s = [];
}
if(!s.t){ // check if s has t
s.t = function(){};
}

Related

'ggbApplet is not defined' error in javascript

I have a web page which include a geogebra applet. On loading the page I would like to modify certain elements in the applet, depending on user input. I tested the following code
<script type="text/javascript">
var parameters = {
"width":600,"height":450,
"filename":"trois_ensembles.ggb"};
var applet = new GGBApplet('5.0', parameters);
window.onload = function() {
applet.inject('applet_container');
ggbApplet.setVisible('A', false);
}
</script>
But the line
ggbApplet.setVisible('A', false);
produces an error in the console
ReferenceError: ggbApplet is not defined
When ggbApplet is referenced elsewhere, as in
<button onclick="ggbApplet.setVisible('A', true)">Set A </button>
everything works as expected.
I don't understand the scope of ggbApplet. Help appreciated.
Checking Global JavaScript section of Scripting page of Geogebra's wiki may be useful.
Cheers.
See this section:
Note: Using any ggbApplet methods in Global JavaScript outside of ggbOnInit will not work as intended since they will be called before the construction is loaded.

Google Scripts/Basic JavaScript - Issue fixed by debugger

I'm working on a Google Scripts add on for Google Sheets, but I'm trying to get the script working before I actually set it up on the sheet. The code below works fine if I set a breakpoint somewhere in the extractNumbers function. If I just execute the code without breakpoints, I get an error:
TypeError: Cannot call method "replace" of undefined. (line 36, file "")
Here's the code:
var myVar = phoneCheck("a1","a2","o1","o2");
Logger.log(myVar);
function phoneCheck(newCell,newHome,oldCell,oldHome) {
Logger.clear();
var newCell = extractNumbers(newCell);
var oldCell = extractNumbers(oldCell);
var newHome = extractNumbers(newHome);
var oldHome = extractNumbers(oldHome);
if (newCell === oldCell) {
return newCell;
exit;
} else if (newCell === oldHome && newHome === oldCell) {
return oldCell;
exit;
}
if (newCell === '' && oldCell !== '' ) {
return oldCell;
exit;
}
if (newCell !== oldCell && newCell !== oldHome) {
return newCell;
exit;
}
return "No value found";
exit;
}
function extractNumbers(input) {
Logger.log(input);
var str = input;
return str.replace( /\D+/g, '');
}
Now I realize my if/then logic is more than a bit inelegant, but for my purposes, quick and dirty is fine. I just need it to run.
ALSO, I have read of other novice JavaScript programmers having similar issues related to the sequence of code execution. If someone would like to link to a concise source aimed at a non-advanced audience, that would be great too. Thanks!
EDIT: I put my code into a new fiddle and it works fine, but it continues to fail in Google Scripts editor unless running in debug mode with a breakpoint. The problem seems to be that the function parameters aren't available to the function unless there is a breakpoint. Anyone have access to Google Scripts that can try my updated code from https://jsfiddle.net/hrzqg64L/ ?
None of the suggestions got to the root of your problem - and neither did your answer, although you've avoided the problem by putting an enclosure around everything.
There's no AJAX, no asynchronous behavior - it's simpler than that. "Shadowing of parameters" is likewise a red herring. Bad coding practice, yes - but not a factor here.
If someone would like to link to a concise source aimed at a non-advanced audience, that would be great too.
Sorry - no such thing. I can explain what's going on, but can't guarantee it will be accessible to novices.
The exception
Let's just clarify what causes the exception, or thrown error, that you've observed.
As written, extractNumbers() will throw an exception if it has a null parameter (or any non-string parameter) passed to it. If you choose to extractNumbers() then hit "run", you'll get:
TypeError: Cannot call method "replace" of undefined. (line 36, file "")
That is telling you that on line 36, which is return str.replace( /\D+/g, '');, the variable str contains an object that is undefined (...and has no replace() method).
For bullet-proof code, you would check your parameter(s) to ensure they are valid, and handle them appropriately. Sometimes that would be with a valid default, and other times you might return an error or throw an exception that is more explicit about the parameter problems.
Running code in Google's debugger
The only way to run code in Google's Debugger is to select a function, then choose "run" or "debug". Assuming you posted all your code, you had just two functions to choose from:
phoneCheck()
extractNumbers()
Whenever Google Apps Script runs any part of a script, the entire script is loaded and scanned to find all symbols & check syntax. The scope of all symbols is noted as well, and so are any dependencies between functions and global symbols (symbols outside of any closure, or block of code).
That takes some time. To speed things up when asked to execute a specific function, the global symbols are only evaluated if they are a dependency for the requested function or the functions it may call. There is another condition that will trigger evaluation of global symbols, and that is if there is a possibility that the debugger may need to stop and display values.
When this happens, any code that is outside a closure (outside a function, for example) will be executed. This is what you observed when you set breakpoints.
Why did it work when breakpoints were set?
As explained, just having a breakpoint set triggers evaluation of global symbols.
You start this script with a few lines of code that are not in any closure:
var myVar = phoneCheck("a1","a2","o1","o2");
Logger.log(myVar);
It is that code which makes the only proper invocation of phoneCheck() with parameters. Because myVar is evaluated, phoneCheck() gets called with parameters, and in turn calls extractNumbers() with a defined parameter.
Unfortunately, because of the way the debugger works, you cannot choose to run that code yourself. You need to rely on these side-effect behaviors.
How to fix this?
Simple. Don't rely on global code to invoke functions under test. Instead, write an explicit test function, and call that.
function test_phoneCheck() {
var myVar = phoneCheck("a1","a2","o1","o2");
Logger.log(myVar);
}
Finally found the issue, but I don't fully understand it.
This question got me thinking about scope and how it might be different in the Google Script environment. I figured a simple workaround would be to enclose the entire script in its own void function, and it worked! Also, I simplified the script quite a bit with an array:
function init () {
var numberArray = ["a3", "a2", "o3", "o10"];
var myVar = phoneCheck(numberArray);
Logger.log(myVar);
function phoneCheck(myArray) {
var phoneString = '';
Logger.clear();
var arrayLength = myArray.length;
for (i = 0; i < arrayLength; i++) {
phoneString += myArray[i].replace(/\D+/g, '');
}
return phoneString;
}
}
Also, I realize the functionality of this script is different than the original, but I was really just trying to solve this problem. Now that I have, I can finish the script properly.
Thanks for all the suggestions, everyone! I learned a lot of good things, even though they turned out not to be the answer.

Defined an array internally, returning undefined when called externally

I have an internal script that has a array defined like so. It also has an external script which reads the data set in the "data" array. I made a mock-up of how I have things set-up, if this is no help I will provide a link to the actual page.
Internal Script:
<script type="text/javascript">
data = {
"id": "1",
"name": "joe"
}
</script>
External Script:
(function(window, document, undefined) {
find = {
postCount: function(){
var user = data.name;
}
};
find.postCount(); // If called here, data is undefined.
})(this, document);
Problem:
If I call the function anywhere but from the console it returns undefined.
I'm still fairly new to javascript so I'm probably making a stupid mistake or something, if you need anymore details let me know. Also, apologies for the quality of the post, it's my first time posting here.
Any help is appreciated, thanks.
shouldn't that be data = { ...?
You may be including the external javascript file before the script block declaring data. Doing this would mean that find.postCount(); is being called before data is declared. Calling it from the console would then work because at that point data is declared.
Note also that calling find.postCount(); shows as returning undefined in the console window when I call it (because the function declares the variable user but never actually returns anything.

Add function to existing JQuery plugin

Is it possible to add a function to a plugin without modifying the actual plugin? Can I do something like this in my site's js file?
$.fn.Watermark.Refresh = function() {
$.Watermark.HideAll();
$.Watermark.ShowAll();
}
or
(function($){
$.fn.Watermark.Refresh = function() {
$.Watermark.HideAll();
$.Watermark.ShowAll();
};
})(jQuery);
neither worked, the first says $ is undefined, the second that jQuery is undefined...
ideas?
Solution: Either method works, just include the jquery file before the site js file.
You can add those functions if you want to, but you'll have to make sure that you're also loading jQuery itself and the plugin to be modified. If you're getting those errors (that jQuery or "$" are not defined), then you have not correctly done that.
Now, though it's true that you can add those functions, I have to wonder what the point would be. If I were to do this, for example:
$.fn.css.myFunction = function() { return "hello world"; };
then it would be possible to call it:
var str = $.fn.css.myFunction();
but so what? What good does that do me? I don't think it's very useful.
Make sure you are including the plugin after jQuery.

JS Closure Compiler - Dont change the function-names

i use the http://closure-compiler.appspot.com/home to compress my code.
MY JS File *EDIT:*
function test_it()
{
// some code
}
MY HTML Code
<div onclick="test_it" />test</div>
My problem is that the compressor rename my function.
When i click (after the compression) on the div i get the error "test_it is not defined". That makes sense coz the function has a new "short" name now.
Is it possible to deactivate "in the Advanced mode" the "rename functions" function?
Or is there a other solution?
Thanks in advance!
Peter
The solution is to bind the click event through javascript:
function test_it() {
// some code
}
document.getElementById("test").onclick = test_it;
HTML:
<div id="test">test</div>
This way the compiler will still change the name of the function (saves space), but it will also change the name of the reference -> problem solved.
Your function has errors in it. You have a closing ) at the end and a ; which is not necessary. It should be:
function test_it()
{
// some code
}
Now if you use the Simple mode you won't have any problems. Be careful with the Advanced mode though as it might perform optimizations and remove this function if not used.

Categories

Resources