Closures / Object References And Private Methods

Aug 22, 2010

I have some confusion about the scripts below:

1) is getRule a local variable or global variable, as it has no var keyword, yet it is an inner function of Validation? So without var, I think global, but being an inner function, I think local. So I'm not sure which.

2) In this line of code: var rule = $.Validation.getRule(types[type]), getRule returns rules, which is just a local variable in Validation. I always see that you return functions, but how does returning a local variable that's just an object literal and not a function be able to return true or false? Now the value of rules is an object literal, and this object returns true or false. So we are basically allowed to use return keyword with local variables that are object literals and not functions?

3) In this line, is foo(age) being called, or is it just being assigned to bar OR is it being called and THEN assigned to bar: var bar = foo(age);

4) Now for the most confusing: age is obviously an object reference as opposed to a literal in the example. Does that make a difference in regards to closures?
Note that I read a number of books, including JavaScript Programmer Reference and Object Oriented JavaScript and jQuery cookbook, which compare primitives vs reference types and how primitive types store directly in memory whereas reference tpyes reference memory, so if one reference changes, they all change where primitive remains ingrained. But when assigning a function as a reference like this, how does that affect the object "age" when passed into bar?

Code:
(function($) {
/*Validation Singleton*/
var Validation = function() {
var rules = {
email : {
check: function(value) {
if(value)
return testPattern(value,".+@.+..+");
return true;
}, .....
$.Validation = new Validation();
})(jQuery);

Code:
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + tmp);
x.memb = x.memb ? x.memb + 1 : 1;
alert(x.memb);
}}
var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);

View 3 Replies


ADVERTISEMENT

Private Methods In Object Literal?

Aug 18, 2010

i have something like this:

Code:
var o = {
f1:function(a) {

[code]....

View 4 Replies View Related

When Closures, Loops, Function References, And Anonymous Functions Interact

Oct 16, 2010

I am confused about the true difference between the two below examples.

first example:

// Demonstrating a problem with closures and loops
var myArray = [“Apple”, “Car”, “Tree”, “Castle”];
var closureArray = new Array();

[code]....

Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed.

I have a couple of problems with this example:

1) I thought a closure is a function that is returned - the inner function is not returned above.

2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function.

3) the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment.

Second example:

// A correct use of closures within loops
var myArray = [“Apple”, “Car”, “Tree”, “Castle”];
var closureArray = new Array();

[code]....

Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray.

This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved?

I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index?

View 7 Replies View Related

Object References

Dec 17, 2005

I am a bit new to JavaScript objects, I have the following object:


LinkTest=function() {
// init
}

LinkTest.prototype.eventHandler=function(){
// the call below fails, as 'this' refers to the link that
// generated the event, and not the instance of LinkTest object
this.doSomething();
}

LinkTest.prototype.register=function(link){
link.onclick = this.eventHandler;
}

LinkTest.prototype.doSomething=function() {
// do something!
}

So basically when you register a link, the onclick event handler gets a reference to LinkTest's eventHandler function. Now when the user clicks on the link, the 'this' refers to the link... how do I reference the instance of LinkTest object from within the eventHandler function?

View 2 Replies View Related

Set A Specific Property On A Private Object?

Feb 16, 2009

I want to be able to set a property on a private object by giving the not notation path to the value. The difficulty is that this object is within closure so I can't access it directly to set the value the normal way (eg. dot.notation.path = 'new value'). This seems weird but I can't think of the obvious way.

Example:

// setter function
function set(path, change){
var privateObject = {
a: 'a',

[Code]....

View 1 Replies View Related

Passing And Using Variables In Object References

Mar 9, 2003

I am trying to make a function that checks/unchecks a checkbox when a specific <td> is clicked. I need to use this same function for several checkboxes in the page so I want to just pass it the name of the checkbox I want to affect as a variable and use it in the object reference lines. BUT, this doesn't work. I can pass the variable to the function as I've used alert(variable) to test this. But it doesn't work when I put it in a line like this "document.forms[0].variable.checked=true;". Code:

View 4 Replies View Related

Object References When Using Bound Event Handlers

Feb 27, 2007

THE QUESTION: How do I get a reference to my Object when processing an
event handler bound to an html element ?

CONTEXT:
Sorry if it is a bit long.

I am developing a JS calendar tool. One of the requirements is that the
calendar will need to display a varying number of months (1..3)
depending on the calling page. Imagine 1, 2 or 3 calendar pages side by
side as required.

I have built a grid object that will contain one month's dates with the
day names at the top. The calendar object inherits the grid object as an
array of "calendar pages" - one grid per month and the calendar provides
the content for each grid. I will use the grid object for another
completely different object later and so I want to use good OOP
encapsulation. The grid is a table generated on the fly and is "dumb" as
far as what it is used for.

I have attached an onlick event to each cell of the grid. Using OOP
priciples I want the calling program (the calendar object in this case)
to provide a function to handle the click and the grid object will
provide to the calendar the row and column of that cell as well as the
grid number (so the calendar can work out which date was clicked since
it knows what the data means and the grid doesnt). Code:

View 6 Replies View Related

Storing Element References As Public Object Members

Sep 20, 2006

I've spent several days trying to work this out. Maybe I'm just
searching for the wrong keywords/phrases.

I have some code that looks like:

[-- snippet starts --]
Console = new Object();
Console.init = function() {
this.STDIN = document.getElementById('console0_stdin');
this.STDOUT = document.getElementById('console0_stdout');

// set styles on the element references, eg:
this.STDIN.style.width = `%'
this.STDOUT.style.width = `%'
}

Console.focus = function() {
this.STDIN.focus();
}

Console.writeln = function(buffer) {
this.STDOUT.value += "
" + buffer;
}

[-- snippet ends --]

I'm not sure why, but the Console.focus() and Console.writeln() methods
just don't seem to be able to use the DOM references stored in
Console.STDIN and Console.STDOUT. Everything's fine in the
constructor, but other methods can't seem to use them.

View 8 Replies View Related

Test Object Equality Using Data Inside - Not References - Possible?

Jan 29, 2009

Is it possible to test whether two objects are equal using the data they contain inside and not comparing their pointers with ==?

Well actually of course there is but...

Is there a way to do it without actually looping through the object, instead maybe something that came with JS? (something like a .equals() method from other programming languages.)

View 5 Replies View Related

Object Methods - Assign A New Function To A Built-in Object In Firefox

Jul 1, 2009

Can assign a new function to a built-in object in Firefox:

But IE and Opera don't have a MouseEvent or HTMLElement that can be set up in the same way. Can you do this in IE or Opera, or just Firefox, and maybe Webkit?

View 1 Replies View Related

Executing Object Methods Is Killing Object Properties

Mar 20, 2010

I created a method for displaying an object's properties:

As long as renderfunction = false, the object is fine coming out of this function.

However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to?

View 1 Replies View Related

Once Set A Private Variable, Test That Object Independently Becomes A Nightmare As The Next Test Is Polluted By The Actions Of The Previous?

Mar 14, 2009

I'm using the standard module pattern and the problem is once you set a private variable, trying to test that object independently becomes a nightmare as the next test is polluted by the actions of the previous.So, the options are to have some reset method (which is horrible), setters on everything (defeats the point) or delete object and re-load script (hideous).

View 2 Replies View Related

Accessing An Object's Methods

Sep 8, 2005

I have a javascript function that needs to access methods of a java
object(localTag). In my JSP I'm trying to include hidden fields for
the Strings returned from the getter method calls of the object like
so:

<html:hidden name="FrmCustomerHolding" property='<%=
"localTag.getTagName()" %>' />
<html:hidden name="FrmCustomerHolding" property='<%=
"localTag.getTagValue()" %>' />

If I can do something like this, what is the correct syntax and how do
I access this property in my javascript? When I have a hidden field
that is just a String, I access it in the javascript like
"document.getElementById("theString").value" and it works fine, but I
can't seem to find how to access the String value of a method call.

View 2 Replies View Related

Using Object Methods In AddEventListener

Jul 20, 2005

When you use addEventListener (or addEvent in IE) to call an object
method, does it call it with the correct this parameter?

The ECMAScript reference has a lot to say about the caller using
Function.prototype.call or Function.prototype.apply and passing the
correct this pointer for the context, but how does addEventListener
determine the correct this pointer. Or does it just punt and pass the
global context, thus making it impossible to refer to the object this
in an object method used as an event listener?

View 6 Replies View Related

Coupling Between Object Methods?

Jun 10, 2011

I have more of a programme design related question here: I have an object with 2 methods, those two methods are supposed to be called repeatedly one after the other (e.g. by setInterval())

window.setInterval(function() {
obj.method1();
obj.method2();
}, 100);

the problem with this code is that the execution time of those methods may increase depending on the processed data (an array with several hundred elements or more) so it may be, that the execution time of both methods exceeds the given repetition time. I could solve that by placing a call to the next function in each method, but I wonder if that is good design or not (tight coupling)

code for method2() is analogue
Obj.prototype.method1 = function ()
{
/* working code here */

[Code]....

View 10 Replies View Related

What Methods Does Every Object Have By Default

Dec 8, 2011

When a custom object is created in javascript, then methods need to be defined for this object. Still every object has toString() method available to them, even if it is not defined. How is this method available to all the objects ? Is it inherited from some root object ?

Is sort() method available to all the objects ? What are the other methiods available to all objects ? Where can I get list of available methods ?

View 1 Replies View Related

Memory Requirements For An Object's Methods

Jul 23, 2005

I am a little confused how the memory for objects is allocated in
JavaScript. David Flanagan, in "javascript: The Definitive Guide,"
states that each property of a class takes up memory space when
instantiated. So space is created for aMethod three times in this
example: Code:

View 9 Replies View Related

JQuery :: Add Methods That Contain 'this' To An Existing Object?

May 18, 2011

Let's say I have a Javascript object that looks like this:

{
events: {
"comments:added": this.add,
"comments:removed": this.remove,
"comments:fetched": this.addAll
}
}

I'd like to add this method to it, either manually, using $.extends() or _.extends():

[Code]...

View 1 Replies View Related

Remembering Object Properties And Methods

Jan 17, 2011

Do many programmers remember most of the object properties and methods or do they use IDE or references to find those specific objects. I'm starting to learn Javascript and seeing all the different type of objects available can be depressing. :(

View 2 Replies View Related

Object Does Not Support Properties Or Methods?

Aug 26, 2009

Code JavaScript:
function dropdown() {
}; dropdown.prototype = {
sele: $('.select'),
city: [],
scope: [],
type: [],
init: function(json) {
if(json.location.length) {
for(var i=0; i<json.location.length; i++) {
this.city[i] = json.location[i].city; .....
this.scope[i] = json.location[i].scope;
}}.....

getUrl: function() {
return location.pathname+location.search;
},
setUrl: function(paramType, param) {
return this.QueryString(paramType) ? this.setQueryString(paramType, param) : this.getUrl()+"&"+paramType+"="+param;
}};

View 2 Replies View Related

Different Ways To Declare Methods/properties Of An Object

Jul 23, 2005

Well, I've been working with JS for three years and have a great experience here. But! I still have no really acceptable answer to the following
question:

What is the principle difference between declaring methods/properties
in the constructor function body and via prototypes.

Are there any real GURUs? Let's discuss the issue.

View 2 Replies View Related

Difference Between Privileged Methods And Object.create

Apr 13, 2010

I'm attempting to understand the use of privileged methods when used with Object.create. I put together a quick demo (code below) that shows what happens when I use Object.create to create a new object based on one that has a privileged method. The outcome is not pleasant, as changing the value in the first object also changes it in the second. Unless I am reading Crockford's articles incorrectly, this makes Object.create almost useless for anything but objects that have only public members.

I've seen many JavaScript programmers use closures extensively to create private members, and that still holds to be a good programming practice. However I still can't find an elegant way to create inheritance in combination with closures in JavaScript, given downfalls such as the one I mentioned above.With all of that said I still think Crockford has a nice way of programming, creating factory functions that produce objects, staying away from the prototype property and making the language look more functional.

Here's the code to demonstrate what I'm referring to. Firebug needs to be enabled to view the console.debug output, otherwise convert them to alerts.

if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}

[code]....

View 3 Replies View Related

Different Methods Of Selecting Some Of The Values In The Json Object

Aug 10, 2011

What are the different methods of selecting some of the values in the json object below:

what different selecting methods can you use to get the date, or the views?

View 2 Replies View Related

JQuery :: Accessing Methods And Properties On An Object Of A Passed Element?

Jan 25, 2010

I have an object on the document element that allows for other components to register with it, i have a custom event something along$(document).bind("register",function(thechild)..So in the child object when they are created i call$(document).trigger("register",this);And indeed i get the DOM object. However i'm looking for the plug in object, i want to be able to call methods on the passed childobject and access it's Config.Does that make sense? How can i write a plug in that is applied to various objects that also registers itself with an 'overseer' object on the document element in such a way that i can allow that overseer object to call methods on any registered child objects?

View 2 Replies View Related

Still Not Getting Closures Right?

Nov 16, 2010

Arg, I'm losing hair. I'm having trouble understanding something extremely basic and important. I have functions who call functions who call functions.. but I'm having trouble doing anything useful with their results. I can't seem to "grab" them. They just get garbage collected. Scope is becoming my enemy.

This is also hard to explain because the code is modular, so stuff is calling stuff is calling stuff.

Everything happens inside a large Object.

[Code]...

Where do I have to go to understand basic Javascript things like getting values back out of a function? It's always the same problem I hit every time I use functions to figure out some value. It's always locked away.

If anyone happens to know of some place where one can practice with these things, that would be nice.Closures for morons? Functions for dummies? Something like that. I've got bookmarks of pages explaining functions and values and closures but I can't seem to take that over to what I want to do with them.

View 6 Replies View Related

Variable Scope And Closures

Jul 23, 2005

Given the following working code:

function attributes() {
var attr1 = arguments[0] || '_'
var attr2 = arguments[1] || '_'
return (
function (el1, el2) {
var value1 = el1[attr1] + el1[attr2];
var value2 = el2[attr1] + el2[attr2];
if (value1 > value2) return 1;
else if (value1 < value2) return -1;
else return 0;
}
);
}

var a = [
{ a:'smith', b:'john' },
{ a:'jones', b:'bob' },
{ a:'smith', b:'jane' }
];
a.sort(attributes('a', 'b'));
for (var i =0; i < a.length; i++) {
document.write(a[i].a + ', ' + a[i].b + '<br>');
}

My question is, are attr1 and attr2 guaranteed to exist through
the lifetime of a.sort(attributes('a', 'b'))?

As I understand it, the anonymous inner function reference I am
returning is a property of attributes(). As such, when I return a
reference to the anonymous inner function, the outer attributes()
function must continue to exist (as must attr1 and att2) until
there are no further references to the inner anonymous function.

As a result, there is no danger of attr1 or attr2 "disappearing"
during the repeated calling of the anonymous inner function.

Is my explanation basically correct, or am I deluding myself and
I'm just lucky that the garbage collector hasn't recovered attr1
or attr2 while the sort is still going on? In other words, is the
behaviour I'm seeing consistent and predictable, or should I
change my approach?

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved