Function nested inside an object property does not execute - javascript

I have a weird behavior on my arms :
I declare an object, properties shall execute in sequence, which they do, but in one there is a simple pass through nothing written in it happens.
Do I have a scope problem ?
Here is a code fragment where verteX is my object
stepsCalcul: function() {
var test = 2;
verteX.testCheck = test*2; //returns undefined
alert('stuff') //alerts nothing
console.log("logged stuff")//logs nothing
verteX.mouseCoordinates();
return true;
},
I sort a jsFiddle aswell
http://jsfiddle.net/AEWrK/3/
Thanks!

Based on your fiddle, you're not calling the init function.
Replace verteX.init; with verteX.init();

Related

I have a button function in my program. Mostly works, but when I click, it doesn't execute the if. Code included

var rectbutton = function(x,y,width,height,bevel,label,basecolor,textcolor,hovercolor,changevar,changevarvalue){
textAlign(CENTER,CENTER);
textSize(height);
fill(basecolor);
rect(x-width/2,y-height/2,width,height,bevel);
fill(textcolor);
text(label,x,y+5);
if(mouseX>=x-width/2 && mouseX<=x+width/2 && mouseY>=y-height/2 && mouseY<=y+height/2){
fill(hovercolor);
rect(x-width/2,y-height/2,width,height,bevel);
fill(textcolor);
text(label,x,y+5);
if(mouseIsPressed){
var changevar=changevarvalue;
}
}
};
Use:
rectbutton(200,250,250,50,5,"PLAY",color(255,255,255),color(0,0,0),color(255,0,0),playerState,1);
Everything works until I click. Doesn't set changevar to changevarvalue. Did try changevar=changevarvalue; instead of var changevar=changevarvalue;
In your code snipped there is no mouseIsPressed defined anywhere, is it missing? You might need to provide us a more complete code example.
Also try to look at your console if any javascript errors occure.
In js objects are passed by reference and primitives are passed by value. If you want to update your changevar variable, you would have to pass an object in changevar parameter while calling the rectbutton function and not some primitive value. I'm assuming playerState contains some primitive and not an object as a value.

Function with sub-functions but also its own... function...?

Please: only pure vanilla JS code. No jQuery or other external things, thank you. :)
How can I create a function that contains sub-functions but also returns a value if no sub-function is called?
For example, let's take a number variable num.
I want to add a round() function to the number variable; if it's called directly, I want it to round up or down depending on the variable's actual value.
var num=4.12;
num.prototype.round=function(){return Math.round(this);}
Now I wand round() to have sub-functions that will round up or down, disregarding the decimal values.
num.prototype.round.up=function(){return Math.ceil(this);}
num.prototype.round.down=function(){return Math.floor(this);}
If I do that and log num.round() to console, it does what it's supposed to. But if I log num.round.up() to console, I get an error telling me that num.round.up() is not a function.
So I try putting the sub-functions into the main function declaration like this:
num.prototype.round=function(){
var n=this;
this.up=function(){return Math.ceil(n);}
this.prototype.round.down=function(){return Math.floor(n);}
return Math.round(n);
}
Then again, num.round() will return the correctly rounded value, but both num.round.up() and num.round.down() will return "not a function" errors.
I'm going nuts trying to figure this out... I didn't only try what I mentioned above, but I also tried doing this with immediately executing functions like this:
num.round=(function(){
return function(){
var that=this;
/* anything in here is already useless because this
is no longer num's value but [Object window]... */
}
})();
I guess part of the trouble is that I'm so weak at OOP that I just have no clue about the correct terminology... naturally, that doesn't help when searching for clues or when it comes to knowing any potential reasons why something like this should not work...
So is there any way at all to do this?
Well you can pass a parameter to the function. Not the exact implementation you want, just an alternative:
var num = function (defaultNumValue) {
var delegation = {
'up': 'ceil',
'down': 'floor'
};
return {
round: function (val) {
return Math[ delegation[val] || 'round' ](defaultNumValue);
}
}
};
var sth = num(1.5);
sth.round(); // 2
sth.round('up'); // 2
sth.round('down'); // 1
May be something like:
function num(n) {
this.num=n;
this.round=Math.round(n);
this.up=Math.ceil(n);
this.down=Math.floor(n);
this.up2=function(){return Math.ceil(n);}
}
var num = new num(4.12);
alert(num.num);
alert(num.round);
alert(num.up);
alert(num.down);
alert(num.up2());

ID Element return when giving as parameter

I am making a website for school and we where working with function. Now i got a litle "problem"
i am using jquery to change the DOM and made a function where you can choose which location you are adding the element to.
Something like this:
function functioname(parameter){
console.log(parameter);
}
when i call this function like this:
functioname("#id");
i will return "#id";
But if i call it like this:
functioname (id);
I get return with the whole div and his children. How can this happen?
And why works this only with divs.
It isn't really a problem i was just wondering how this works.
Thanks in advance if somebody could explain what is happening here.
The window.id will find a DOM element whose id it matches. For example, window.mydiv will find:
<div id="mydiv"></div>
However, this not a recommended practice.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().
http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object
In the first function you are passing the string and in the second example you are passing the window object. Same as we pass an object with "this"
<div onclick= " functionname(this); "> </div>
here we get the complete object inside the function.
In first line of code "#id" you are passing the string. it's return the string also as you says.
in second you pass object id that you have earlier in your code. This is maybe why you got the different result.
Let's take a look at the window object. The window is pretty cool in that it allows you to declare global variables from anywhere on the fly. Take the following code for example
//the following three lines of code do the same thing
//create a global variable and store a value in it
window.a = 1;
window["b"] = 2;
var c = 3; //this one is most used though
function g() {
//the following three lines of code do not do the same thing
window.d = 4; //global
window["e"] = 5; //global
var f = 6; //local
}
g();
console.log(a); //prints 1
console.log(b); //prints 2
console.log(c); //prints 3
console.log(d); //prints 4
console.log(e); //prints 5
try {
console.log(f); //ERROR
} catch (err) {
console.log(err);
}
console.log(window.a); //prints 1
console.log(window.b); //prints 2
console.log(window.c); //prints undefined
console.log(window.d); //prints 4
console.log(window.e); //prints 5
console.log(window.f); //prints undefined
console.log(window["a"]); //prints 1
console.log(window["b"]); //prints 2
console.log(window["c"]); //prints undefined
console.log(window["d"]); //prints 4
console.log(window["e"]); //prints 5
console.log(window["f"]); //prints undefined
It is important to know that obj.prop === obj["prop"] is always true in JavaScript. That is why the last two sets of tests have the same results. Also important is prop === window.prop unless you declared prop using var prop;. This is because JavaScript secretly uses the special keyword using on the window variable at all times unless otherwise specified.
All browsers make DOM elements available via id using document.getElementByID but some browsers are nice enough to set up some variables for you so you don't have to write all that code. Imagine that a browser runs this script before any of your scripts do
(function(context) {
var tags = document.getElementsByTagName("*");
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.id) {
context[tag.id] = tag;
}
}
}(window));
Which fills the window variable / global scope with tags that have ids.
Here are a bunch of examples. http://jsfiddle.net/Lk345zez/

Modified value in a function is not seen in another function

In the following code, check executes first and sets this.canClick to false. Then resetClick sets this.canClick to true after this.clickDelay seconds. However, the change is not seen in when check is called again. I logged the value of this.canClick in both functions: resetClick logs true, then check logs false for the same variable.
this.resetClick=function(){
this.canClick=true;
};
this.check=function(){
if (isMouseDown&&this.canClick==true){
if (mouse.x>=this.x-this.sizex/2 && mouse.x<=this.x+this.sizex/2 && mouse.y>=this.y-this.sizey/2 && mouse.y<=this.y+this.sizex/2){
this.text=this.callback();
this.canClick=false;
setTimeout(this.resetClick, this.clickDelay);
}
}
};
I don't believe it is a scope problem, because both are member functions of the same object and are modifying a property of that object. Also, in case you're wondering, that is a function to check if a button is clicked, and do "debouncing" so you don't click the same button twice by mistake.
EDIT: Important missing information: If I just call resetClick, without using setTimeout, it works.
It is indeed a scope issue.
this inside the function does not refer to the object which will contain the function later.
You should bypass it with this one simple trick (tm): use an alias for this
var that = this;
this.resetClick=function(){
that.canClick=true;
};
this.check=function(){
if (isMouseDown&&that.canClick==true){
if (mouse.x>=that.x-that.sizex/2 && mouse.x<=that.x+that.sizex/2 && mouse.y>=that.y-that.sizey/2 && mouse.y<=that.y+that.sizex/2){
that.text=that.callback();
that.canClick=false;
setTimeout(that.resetClick, that.clickDelay);
}
}
};
The method you are calling with setTimeout is run outside of the object scope, so this will only refer to the global window object at the time the method is executed (and that means this.canClick will be window.canClick actually).
Use a closure to preserve the value of this inside the object.

getting the name of a variable through an anonymous function

Is it possible to find the name of an anonymous function?
e.g. trying to find a way to alert either anonyFu or findMe in this code http://jsfiddle.net/L5F5N/1/
function namedFu(){
alert(arguments.callee);
alert(arguments.callee.name);
alert(arguments.callee.caller);
alert(arguments.caller);
alert(arguments.name);
}
var anonyFu = function() {
alert(arguments.callee);
alert(arguments.callee.name);
alert(arguments.callee.caller);
alert(arguments.caller);
alert(arguments.name);
}
var findMe= function(){
namedFu();
anonyFu();
}
findMe();
This is for some internal testing, so it doesn't need to be cross-browser. In fact, I'd be happy even if I had to install a plugin.
You can identify any property of a function from inside it, programmatically, even an unnamed anonymous function, by using arguments.callee. So you can identify the function with this simple trick:
Whenever you're making a function, assign it some property that you can use to identify it later.
For example, always make a property called id:
var fubar = function() {
this.id = "fubar";
//the stuff the function normally does, here
console.log(arguments.callee.id);
}
arguments.callee is the function, itself, so any property of that function can be accessed like id above, even one you assign yourself.
Callee is officially deprecated, but still works in almost all browsers, and there are certain circumstances in which there is still no substitute. You just can't use it in "strict mode".
You can alternatively, of course, name the anonymous function, like:
var fubar = function foobar() {
//the stuff the function normally does, here
console.log(arguments.callee.name);
}
But that's less elegant, obviously, since you can't (in this case) name it fubar in both spots; I had to make the actual name foobar.
If all of your functions have comments describing them, you can even grab that, like this:
var fubar = function() {
/*
fubar is effed up beyond all recognition
this returns some value or other that is described here
*/
//the stuff the function normally does, here
console.log(arguments.callee.toString().substr(0, 128);
}
Note that you can also use argument.callee.caller to access the function that called the current function. This lets you access the name (or properties, like id or the comment in the text) of the function from outside of it.
The reason you would do this is that you want to find out what called the function in question. This is a likely reason for you to be wanting to find this info programmatically, in the first place.
So if one of the fubar() examples above called this following function:
var kludge = function() {
console.log(arguments.callee.caller.id); // return "fubar" with the first version above
console.log(arguments.callee.caller.name); // return "foobar" in the second version above
console.log(arguments.callee.caller.toString().substr(0, 128);
/* that last one would return the first 128 characters in the third example,
which would happen to include the name in the comment.
Obviously, this is to be used only in a desperate case,
as it doesn't give you a concise value you can count on using)
*/
}
Doubt it's possible the way you've got it. For starters, if you added a line
var referenceFu = anonyFu;
which of those names would you expect to be able to log? They're both just references.
However – assuming you have the ability to change the code – this is valid javascript:
var anonyFu = function notActuallyAnonymous() {
console.log(arguments.callee.name);
}
which would log "notActuallyAnonymous". So you could just add names to all the anonymous functions you're interested in checking, without breaking your code.
Not sure that's helpful, but it's all I got.
I will add that if you know in which object that function is then you can add code - to that object or generally to objects prototype - that will get a key name basing on value.
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
And then you can use
THAT.getKeyByValue(arguments.callee.caller);
Used this approach once for debugging with performance testing involved in project where most of functions are in one object.
Didn't want to name all functions nor double names in code by any other mean, needed to calculate time of each function running - so did this plus pushing times on stack on function start and popping on end.
Why? To add very little code to each function and same for each of them to make measurements and calls list on console. It's temporary ofc.
THAT._TT = [];
THAT._TS = function () {
THAT._TT.push(performance.now());
}
THAT._TE = function () {
var tt = performance.now() - THAT._TT.pop();
var txt = THAT.getKeyByValue(arguments.callee.caller);
console.log('['+tt+'] -> '+txt);
};
THAT.some_function = function (x,y,z) {
THAT._TS();
// ... normal function job
THAT._TE();
}
THAT.some_other_function = function (a,b,c) {
THAT._TS();
// ... normal function job
THAT._TE();
}
Not very useful but maybe it will help someone with similar problem in similar circumstances.
arguments.callee it's deprecated, as MDN states:
You should avoid using arguments.callee() and just give every function
(expression) a name.
In other words:
[1,2,3].forEach(function foo() {
// you can call `foo` here for recursion
})
If what you want is to have a name for an anonymous function assigned to a variable, let's say you're debugging your code and you want to track the name of this function, then you can just name it twice, this is a common pattern:
var foo = function foo() { ... }
Except the evaling case specified in the MDN docs, I can't think of any other case where you'd want to use arguments.callee.
No. By definition, an anonymous function has no name. Yet, if you wanted to ask for function expressions: Yes, you can name them.
And no, it is not possible to get the name of a variable (which references the function) during runtime.

Categories