Catching on with JS Objects - javascript

guys!
I'm giving my firsts steps in JS and in OOP in general, and I am trying to build code perhaps too stilized for my level, but I would like my sets and gets to be like "object.a" and "object.a = value" and not call them "getA" and "setA" and, above all, definitively not like a function ("object.a()" and "object.a(value)").
I design this page to find my way of doing but it is driving me crazy:
I don't know why "wa" keeps on incrementing it's value till it flips out with the message "too much recursion".
I don't see how to do for get a and set a to see "a" inside of "coso".
Can anybody help me?
Here's my code:
<!doctype html>
<html>
<head>
<link href="/style.css" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<style>
</style>
<script>
function coso() {
var a = 1024;
coso.prototype = {
get a() {return this.a},
set a(valor) {this.a = valor}
}
this.muestraA = function() {if(a === this.a) {alert("¡Yupi!")} else alert("A vale: " + a +", pero a vale: " + this.a)}
}
function GuardaA(valor) {
var obj = new coso();
obj.a = valor;
obj.muestraA();
return obj.a;
}
</script>
<title>Prueba Objeto</title>
</head>
<body>
<h1>Prueba Objeto</h1>
<form onchange="x.value=GuardaA(wa.value)">
<label for="wa">Valor para A</label>
<input type="number" id="wa">
<label for="x">A vale:</label>
<output id="x" for="wa"></output>
</form>
<footer></footer>
</body>
</html>

You're getting infinite recursion because the get a() function tries to read this.a. But this is the object that has the get a() function, so it calls that function again, and so on repeatedly.
You should be accessing the local variable a, because the whole point of defining a getter and setter is because you want to use that variable instead of a regular property.
function coso() {
var a = 1024;
coso.prototype = {
get a() {return a;},
set a(valor) {a = valor;}
}
this.muestraA = function() {
if(a === this.a) {
alert("¡Yupi!");
} else {
alert("A vale: " + a +", pero a vale: " + this.a);
}
}
}

Related

when i try to access array element by index it gives me undefined

i created an array and insert elements by array.push(). when i console.log(array) it gives me following out put output of console.log(array)
when i console.log(array[0]) it gives me undefined. why is happing and a blue i tag appear in picture which says "this value was evaluated on first expanding it may have changed since then in array javascript" what does means. please help me to understand the problem
here the full code
index.html =>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>zip reader</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<body>
<h3>Choose the local(s) zip file(s)</h3>
<input type="file" id="file" name="file" multiple /><br />
<div id="result_block" class="hidden">
<h3>Content :</h3>
<div id="result">
</div>
</div>
</body>
<script src="jszip.min.js"></script>
<script src="jszip-utils.min.js"></script>
<script src="app1.js"></script>
<script src="FileSaver.min.js"></script>
</html>
app1.js =>
var array = []
var contents = []
var $result = $("#result");
$("#file").on("change", function(evt) {
// remove content
$result.html("");
// be sure to show the results
$("#result_block").removeClass("hidden").addClass("show");
// Closure to capture the file information.
function handleFile(f) {
var $title = $("<h4>", {
text : f.name
});
var $fileContent = $("<ul>");
$result.append($title);
$result.append($fileContent);
var dateBefore = new Date();
JSZip.loadAsync(f) // 1) read the Blob
.then(function(zip) {
var dateAfter = new Date();
$title.append($("<span>", {
"class": "small",
text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
}));
zip.forEach( function (relativePath, zipEntry) {
var y = zipEntry.name
array.push(y);
$fileContent.append($("<li>", {
text : zipEntry.name
}));
});
}, function (e) {
$result.append($("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + f.name + ": " + e.message
}));
});
}
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
handleFile(files[i]);
}
console.log(array[0])
});
When you console.log an object (including arrays), it isn't being serialized, and only a reference is passed to a console. When you expand it, this reference is used to check the state of this object.
Most probably what's happening is the following sequence:
console.log(array) // passes array reference to a console
console.log(array[0]) // prints undefined immediately
array.push(...) // an actual array modification
you expand the object, and console checks the content of an array
PS.
It's reasonable to ask, what will happen, if the reference will become invalid due to any reason.
For browsers - it's simpler, since the console and JS program run under same parent process, browser is responsible for everything.
But if you'll ever try to debug Node process, which has the same API of passing the reference, you will face strange issues all over around, like this one: No debug adapter, can not send 'variables VSCODE

Deriving value from textfield to javascript(DOM issue)!

In my palindrome checker, i can't obtain value from the HTML input text-field. I tried various methods including query-selectors. But nonetheless is working. Error in the validator is document.getElement(...) is null.
i need to find whats wrong with my code. Is there any problem in my DOM?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i = document.getElementById('boiler').value;
function check_pal() {
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
I am little sure that my problem is with document model. Because i get correct result when i directly assign the value to the variable. Or else i get "undefined is not a palindrome"
Update your script to following
<script>
function check_pal() {
// move this line inside the function
var i = document.getElementById('boiler').value;
// rev(); // Also removed this un-necessary call
if (i == rev(i)) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
// modify function to take input as argument rather than relying on global variable
function rev(i) {
i = i + "";
return i.split("").reverse().join("");
}
</script>
Reasoning - When you manually assigned the value of i, then it was running correctly. However, when were trying to read it from the getElementById, the element did not existed by then and it throws a JS error (cannot read property 'value' of null), hence, the error (as i was never initialized and remains undefined). Move the retrieving of value inside the function where the latest value can be retrieved and stored in i.
This should solve it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i;
function check_pal() {
i = document.getElementById('boiler').value;
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
Now the i variable gets assigned in the check_pal function and declared in the global space so both functions can access it. I think you should take a close look in scope in javascript.

Map demo in Javascript

Found and fixed my own error. The problem was that I've had another variable called "map" in a different document, so with that being around my code didn't work.
I'll just leave this code here as an example of how to do a map.
<html>
<head>
<script type="text/javascript">
var map = {};
map["red"] = "not avaliable";
map["blue"] = "avaliable";
function car(color){
this.color = color;
}
function initialize(){
var testCar = new car("blue");
alert("Value is obviously blue: " + testCar.color);
if (testCar.color in map) {
var mappedValue = map[testCar.color];
console.log("Your car in "+ testCar.color + " is "+ mappedValue);
} else {
console.log("No color "+ testCar.color + "in maps");
}
}
</script>
</head>
<body onload="initialize()"></body>
</html>
Problem solved. Be careful you don't have variables with the same name even in different documents.

How Do You Run the ENTIRE Javascript Page From An Button In HTML?

I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>

How can I change global variables in javascript?

My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?
var a = 5;
var b = 16;
var c = 27;
function reset(){
a = 0;
b = 0;
c = 0;
}
My html code to call the function:
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
</form>
</html>
Javascript code to show the variables:
function display(){
document.write("A is equal to " + a + "<br/>");
document.write("B is equal to " + b + "<br/>");
document.write("C is equal to " + c );
}
Html to display the variables
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
</form>
</html>
change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.
http://www.w3schools.com/jsref/met_form_reset.asp
There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global variable.
That can`t work, because you are asserting that variables in function scope. But your variables are currently stored in global scope (window), so this code will work:
var a = 5;
function reset() {
console.log(window.a); // 5
window.a = 10;
}
reset();
console.log(a); // 10

Categories