Javascript inheritance infinite loop - javascript

I create this block of code in javascript:
function Shape() {}
Shape.prototype.name = "Shape";
Shape.prototype.toString = function() {
result = [];
if(this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
}
function twoDShape() {};
twoDShape.prototype = new Shape();
twoDShape.prototype.constructor = twoDShape;
twoDShape.uber = twoDShape.prototype;
twoDShape.name = "twoD Shape";
var a = new twoDShape();
console.log(a.toString());
I don't know why but when I run it, firefox is freeze. I've been trying hours to figure it out. And my guess is there should be an infinite loops in my code and it lives somewhere in the if condition, but I didn't find it out. Could someone help me out of this headache.
Thank you!

When you call this.constructor.uber.toString() from Shape.prototype.toString, uber is twoDShape.prototype which is a Shape, and so that toString method is Shape.prototype.toString again.
And that causes an infinite loop.

well, after trying a fair amount of test, I finally got a clue. And I believe this is a answer for my own question above. Typing: a.constructor.uber.constructor === twoDShape in firefox, it returns true. And that's why it causes infinite loop.

Related

Javascript, factorial , too difficult

var fact = (function(){
var cache = {'0': 1};
var func = function(n){
var result = 0;
if(typeof(cache[n]) === 'number'){
result = cache[n];
}
else{
result = cache[n] = n * func(n-1);
}
return result;
}
return func;
})();
console.log(fact(5)); //120
The code is this.
I can't understand this code, wholly.
It's look like add cache, and add cache
but how does this work?
Don't we need for loop to add cache?
also, return func; <- what's is this?
please explain wholly
The code is more complex than is needed. The cache array isn't being used as cache; it's being used as a means of hardcoding the fact that the factorial of 0 is 1. The recursion loop doesn't need to add to the cache, but if the extra line to do so were added, then the array would really function as a cache, and it would provide performance improvements on subsequent calls to the function.

I want to know what condition to write in while loop

var understand = true;
while(/* ... */) {
console.log("I'm learning while loops!");
understand = false;
}
I want to print "I'm learning while loops!" so what condition need to write in loop?
Try this:
while(understand){
console.log("I'm learning while loops!");
understand = false;
}
Edit1:
If you want your loop to run for number of times:
var i=0;
while(i<10){ //suppose you want to run your loop for 10 times.
console.log("I'm learning while loops!");
i++;
}
Edit2: (Reply to code in comments)
You are using loop as a function name and checking same in the while loop which is wrong.
Try this:
var myFunctionName = function()
{
var myVariableName = 0;
while(myVariableName<3)
{
console.log("In loop" + myVariableName);
myVariableName++;
}
};
myFunctionName();
Try this to execute your while loop once.
var understand = false; // not yet
while(understand !== true){
console.log("I'm learning while loops!");
understand = true; // I do now!
}
var understand = true;
while( understand == true){
console.log("I'm learning while loops!");
understand = false;
}
The while loop will continue to execute while the condition evaluates to true. So it really depends on the condition you want. If you just want a single loop, and judging by your code, you probably want the following:
var understand = true;
while(understand) {
console.log("I'm learning while loops!");
understand = false;
}
This is like saying: "while understand equals true, then execute the loop"
It is worth mentioning that the variable name understand doesn't make much sense starting as true and being set to false when you want to break the loop (assuming that you want to break the loop when you do understand). So the following would be more logical:
var understand = false;//don't yet understand, so enter loop
while(!understand) {
console.log("I'm learning while loops!");
understand = true;//now I understand, so break loop
}
This is like saying: "while understand equals false, then execute the loop"

JavaScript - shorten math function

function randomize() {
var ra = Math.floor(Math.random()*ar.length=4);
document.getElementById('es').innerHTML = ar[ra];
}
Is there a way to short this code even more than it is? The reason why is because I'm going to be using this code a lot in other projects and objects and I cannot just call it inside like this: randomize(); because I have diffrent arrays.
function randomize() {document.getElementById('es').innerHTML = ar[Math.floor(Math.random()*ar.length)];}
But you wanted to use it more without a function call:
function $(id) {
return document.getElementById(id);
}
function randomize() {
$('es').innerHTML = ar[Math.floor(Math.random()*ar.length)];
}
And instead of Math.floor, you can use ~~ for a microscopical faster diffrence.
This saves some space and time if you are going to use it more. But if only one time, use the first example.
Without knowing what, precisely, you're doing, I'd suggest passing the relevant arguments into the function as parameters:
function randomize(el, array){
if (!el || !array){
return false;
}
else {
var ra = Math.floor(Math.random() * array.length=4);
// please note that I don't understand what's happening in the above line
// and suspect, quite strongly, that the '=4' was a typo. Correct as necessary
el.innerHTML = ar[ra];
}
}
// call:
randomize(document.getElementById('es'), ['1','2']);
/* or:
var el = document.getElementById('es'),
array = ['one','two'];
randomize(el,array);

Sleep in javascript - no setTimeout [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 7 years ago.
All those setTimeout answers here don't work!
I just want to wait a few seconds between two functions, like this:
do_fn1();
wait(5000);
do_fn2();
From phpied.com:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
I don't think you can. You'll probably have to
do_fn1();
window.setTimeout(do_fn2, 5000);
Two thoughts:
first of all why not wrap up all of the post delay statements into a wrapper function
var postDelayFunc = function(){
dosomething();
dosomethingelse();
onemorething();
}
then in your code pass this function as the parameter to setTimeout.
//your code
dofunc1();
setTimeout(postDelayFunc, 1000);
Alternatively take a look at jQuery deferred: http://msdn.microsoft.com/en-us/scriptjunkie/gg723713, although you will probably end up writing very similar code.
One thing struck me though about your responses to other answers and possibly where the confusion arises. I think you are looking at your function and seeing a single thread you just want to hold up for a while before carrying on.
You should not do this though in javascript as it ties up the entire browser and will annoy the hell out of users. Instead what you are in effect doing when you use setTimeout, is indicating that when the timeout expires another thread will pick up and execute the passed in function.
As soon as the timeout has been set, the executing thread will continue with the next line (which is why you think the timeout isn't working). What you probably need to do, is set the timeout, and put ALL the post-execution steps into the function handed off to the timer as indicated above.
Saying they all don't work without an example is big call because I'm sure they probably do.
How about this,
do_fn1();
setTimeout(do_fn2, 5000);
All those setTimeout answers here don't work!
Of course they do:
function a() {
alert("I'm pretty sure...");
}
function b() {
alert("...that they work just fine.");
}
a();
setTimeout(b, 5000);
Another hack I will probably use, however personally I would not recommend it.
Check out here http://jsfiddle.net/S6Ks8/1/
function parseSleeps(func){
var fdef = func.toString();
var fbody = fdef.match(/\{([\s\S]*)\}/)[1].split(/sleep\(.*?\)\;?/);
var sleeps = fdef.match(/sleep\((.*?)\)/g);
var fargs = fdef.match(/\(([\s\S]*?)\)/)[1];
var fbodyNew = [];
var times = [];
fbodyNew.push(fbody.shift(), '\n');
for(var i = 0; sleeps && i < sleeps.length; i++){
var sec = sleeps[i].match(/\d+/)[0];
times.push(sec);
fbodyNew.push('setTimeout(function(){\n');
fbodyNew.push(fbody.shift(), '\n');
}
while(times.length){
var sec = times.pop();
fbodyNew.push('}, ', sec, ');\n');
}
return new Function(fargs, fbodyNew.join(''));
}
// Your code from here
function a(str1, str2){
alert(str1);
sleep(3000);
alert(str2);
}
var func = parseSleeps(a);
func('here', 'there');
The smartest way would be to have something like
function a() {
// Do stuff
setTimeout(b, 42)
}
function b() {
// Do other stuff delayed
}
Never "block" any Threads in JS - if you think you have to do there is definately a "cleaner" way to do achieve your aim.

Javascript code as a variable

Ok, this may sound a bit crazy but hear me out :)
I would like to do the following in javascript:
define START_OF_EVERY_FUNCTION = "try {"
define END_OF_EVERY_FUNCTION = "} catch () {}"
function TEST () {
START_OF_EVERY_FUNCTION
// rest of function
END_OF_EVERY_FUNCTION
}
Basically, can I define a list of javascript lines (code) and include them as above? I'm looking for a technique versus comments about whether this is a good idea or not or debate over wrapping all functions in a try/catch block.
I know about eval(), but I dont think you can eval statements like the above.
This might be goofy but you could define a master function and run other functions through it by passing them in.
var execute = function(func){
alert('before');
func();
alert('after');
};
function sayHi(){
alert('hi there');
}
execute(sayHi);
As requested, an example with passing arguments.
var execute = function(func){
alert('before');
var ret = func.apply(null, Array.prototype.slice.call(arguments, 1));
alert('after');
};
function saySomething(sayWhat){
alert(sayWhat);
}
execute(saySomething,'hey there');
That is not allowed in JavaScript.
You could extend the Function prototype:
Function.prototype.tryThis = function() {
try {
this();
}catch(ex){
alert('Caught '+ex);
};
};
function tryIt() {
alert('Inside tryIt');throw "My Error from tryIt";
}
tryIt.tryThis();
You need to look into aspect oriented programming for JavaScript. You can create hooks for function entry and exit. Tools like JSUnit do this for example.
I think you can do this with the "new Function" operator. I've never used it myself, since I'm not clinically insane, but I believe you can pass it a string which it will evaluate and use as the function body. You can also get the code for each function by calling myFunction.toString(). So put together, it'd be something like this:
var functionsToMessUp = ['myFunc1', 'myFunc2'];
for (var i = 0; i < functionsToMessUp.length; ++i) {
var theFunc = window[functionsToMessUp[i]]; // assuming they're in global scope
window[functionsToMessUp[i]] = new Function(
START_OF_EVERY_FUNCTION
+ theFunc.toString()
+ END_OF_EVERY_FUNCTION
);
}
Now, the above almost certainly won't work - there's parameters and other things to take into consideration, and I don't even think that's how the new Function constructor works, but if you really want to go down this path (which I really don't recommend), then this might be a good starting point for you.
Maybe something like this?
function tryCatch(callback) {
try {
callback();
} catch() {}
}
var myFunction = function() {
// do some stuff
};
tryCatch(myFunction);

Categories