473,326 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

FYI: Priveleged method gotcha

OK, wanted to make a more positive contribution to start than just
plonking somebody. Here's something I've discovered using "priveleged
methods" a la Douglas Crockford
(http://crockford.com/javascript/private.html):

If you want a constructor to utilize priveleged methods the methods must
be defined in the constructor ABOVE where they are called. Consider the
following:

function ExaminableField(element, examCriteria)
{
var formElement = element;
var name = element.name;
var required = true;

//must be defined before used privately
this.isRequired = function()
{
if (arguments.length == 1)
{
required = arguments[0]
}
return required;
}

if (!!examCriteria)
{
this.isRequired(examCriteria.required);
}

}

It had been causing an error when I had my if block above the definition
of this.isRequired. Thought this might help somebody, and/or contribute
to a proper convention.
Jul 20 '05 #1
12 2631
> OK, wanted to make a more positive contribution to start than just
plonking somebody. Here's something I've discovered using "priveleged
methods" a la Douglas Crockford
(http://crockford.com/javascript/private.html):

If you want a constructor to utilize priveleged methods the methods must
be defined in the constructor ABOVE where they are called.
It is generally a good thing to define things before using them. This is
particularly true in a dynamic language like JavaScript, where the WHEN of a
definition is significant. The critical thing is BEFORE. Often that means ABOVE,
but not always.
if (!!examCriteria)


!! converts its operand to a boolean. If it was falsy, it produces false,
otherwise it produces true. But in an if, falsy values are ok, so the !! is
wasted. It is better to write

if (examCriteria)

Jul 20 '05 #2
"George Jempty" <ch*****@highstream.net> wrote in message
news:Oi**************@fe01.atl2.webusenet.com...
<snip>
Here's something I've discovered using "priveleged
methods" a la Douglas Crockford
(http://crockford.com/javascript/private.html):

If you want a constructor to utilize priveleged methods the
methods must be defined in the constructor ABOVE where they
are called. Consider the following:

function ExaminableField(element, examCriteria)
{
var formElement = element;
var name = element.name;
var required = true;

//must be defined before used privately
this.isRequired = function()
{
if (arguments.length == 1)
{
required = arguments[0]
}
return required;
}

if (!!examCriteria)
This double NOT (- !! -) is a nice construct as it produces a boolean
that represents the type-converted true-ness of its right-most operand.
Useful to flag the existence of a browser feature to avoid having to
have it type-converted for multiple subsequent tests:-

var useGetById = !!document.getElementById;

( compared with clunkier looking alternatives like:-
var useGetById = (document.getelementById)?true:false;
)

- but it is not needed here. The first - ! - will have to type-convert
its operand to a boolean value prior to inverting it, the second - ! -
will then invert that boolean and produce the value used to resolve
the - if - statement. However, if the identifier was used directly
within the if statement it would be type-converted to boolean to resolve
the - if - statement, so - if(examCriteria) - must always produce the
same results as - if(!!examCriteria) - but fractionally quicker.
{
this.isRequired(examCriteria.required);
}

}

It had been causing an error when I had my if block above the
definition of this.isRequired. Thought this might help
somebody, and/or contribute to a proper convention.


Because the function assigned to - this.isRequired - is a function
expression it is evaluated inline as the constructor executes so there
would be no value assigned to - this.isRequired - prior to the execution
of the assignment.

In contrast, inner function definitions (private methods in class based
OO terminology) are evaluated during the creation of the "variable"
object as the script enters the execution context for the function
call[1]. So it should be possible to call such a function in code that
physically precedes its definition and also render that function object
privileged by assigning a reference to it to a public object member:-

function ExaminableField(element, examCriteria){
var formElement = element;
var name = element.name;
var required = true;

if(examCriteria){
_requed(examCriteria.required);
}

this.isRequired = _requed;

function _requed(){
if(arguments.length == 1){
required = arguments[0]
}
return required;
}
}

- Doing so seems unnecessary. I would just put up with having to write
the constructor in the required order if I wanted the method to be
privileged.

[1] The Mozilla/Gecko implementation seems to be a bit off spec (ECMA
262 3rd Edition) in this respect as it handles inner function
definitions contained within blocks, such as - if(x){ function doX(){
.... } } - as if they were inline in some sense. It would be unusual to
be using inner function definitions in that way so there should be no
significant consequences.

Richard.
Jul 20 '05 #3
>
This double NOT (- !! -) is a nice construct as it produces a boolean
that represents the type-converted true-ness of its right-most operand.
Useful to flag the existence of a browser feature to avoid having to
have it type-converted for multiple subsequent tests:-

var useGetById = !!document.getElementById;

( compared with clunkier looking alternatives like:-
var useGetById = (document.getelementById)?true:false;
)


I realise this is a bit OT but I find the double-not it very useful when
validating combinations of values. For instance, if the user can specify
either parameter a or parameter b but not both, we can write

if ( !!a != !!b) {
parameters are valid
}

obviously != transliterates into XOR. more elaborate validation rules are
easily expressed in this way when the longhand logic would be near
impossible to comprehend.

This also technique is also handy in C and java.

Andy
Jul 20 '05 #4
"Andy Fish" <aj****@blueyonder.co.uk> wrote in message
news:ho********************@news-text.cableinet.net...
<snip>
... I find the double-not it very useful when
validating combinations of values. For instance,
if the user can specify either parameter a or
parameter b but not both, we can write if ( !!a != !!b) {

<snip>

Consider:-
(best viewed with fixed width font)

a | b | a != b |
true | false | true |
false | true | true |
true | true | false |
false | false | false |

!a | !b | !a != !b |
false | true | true |
true | false | true |
false | false | false |
true | true | false |

!!a | !!b | !!a != !!b |
true | false | true |
false | true | true |
true | true | false |
false | false | false |

Obviously - "aString != "anotherString" - is true, while - !"aString" !=
!"anotherString" - is false as both strings will type-convert to boolean
true (and then be inverted to false by the - ! - operator). So at least
one type-conversion to boolean is needed to do the comparison when a and
b are not boolean to start with. But it looks like - !a != !b - will
always produce the same results as - !!a != !!b - as the result of -
!something - is always boolean.

Richard.
Jul 20 '05 #5
Richard Cornford wrote:
"George Jempty" <ch*****@highstream.net> wrote in message
news:Oi**************@fe01.atl2.webusenet.com...
<snip>
Here's something I've discovered using "priveleged
methods" a la Douglas Crockford
(http://crockford.com/javascript/private.html):

If you want a constructor to utilize priveleged methods the
methods must be defined in the constructor ABOVE where they
are called. Consider the following:

function ExaminableField(element, examCriteria)
{
var formElement = element;
var name = element.name;
var required = true;

//must be defined before used privately
this.isRequired = function()
{
if (arguments.length == 1)
{
required = arguments[0]
}
return required;
}

if (!!examCriteria)

This double NOT (- !! -) is a nice construct as it produces a boolean
that represents the type-converted true-ness of its right-most operand.
Useful to flag the existence of a browser feature to avoid having to
have it type-converted for multiple subsequent tests:-

var useGetById = !!document.getElementById;

( compared with clunkier looking alternatives like:-
var useGetById = (document.getelementById)?true:false;
)

- but it is not needed here. The first - ! - will have to type-convert
its operand to a boolean value prior to inverting it, the second - ! -
will then invert that boolean and produce the value used to resolve
the - if - statement. However, if the identifier was used directly
within the if statement it would be type-converted to boolean to resolve
the - if - statement, so - if(examCriteria) - must always produce the
same results as - if(!!examCriteria) - but fractionally quicker.


I use !! because examCriteria, or any other variable for that matter,
might contain 0 or "", and I don't necessarily want these values to
evaluate as false.

George Jempty
Jul 20 '05 #6
George Jempty wrote:


I use !! because examCriteria, or any other variable for that matter,
might contain 0 or "", and I don't necessarily want these values to
evaluate as false.


Never mind....major brain fart
Jul 20 '05 #7
George Jempty <ch*****@highstream.net> writes:
I use !! because examCriteria, or any other variable for that matter,
might contain 0 or "", and I don't necessarily want these values to
evaluate as false.


But they do.
!!0 === false
!!"" === false
!!null === false
!!undefined === false
!!NaN === false

The conversion performed by !! is exactly the same as the one
performed by the function Boolean or implicitly by a conditional (if,
while, do/while, ?:).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #8
Yep
"Richard Cornford" <Ri*****@litotes.demon.co.uk> wrote in message news:<bh*******************@news.demon.co.uk>...
[1] The Mozilla/Gecko implementation seems to be a bit off spec (ECMA
262 3rd Edition) in this respect as it handles inner function
definitions contained within blocks, such as - if(x){ function doX(){
... } } - as if they were inline in some sense.


But they are! A function declaration is _illegal_ in a block
statement, therefore a function defined as you describe could be only
a function expression, not a function declaration, and should
therefore be processed as an expression. Guess which browser is a bit
off spec ;-)
Regards,
Yep.
Jul 20 '05 #9
"Richard Cornford" <Ri*****@litotes.demon.co.uk> wrote in message
news:bh*******************@news.demon.co.uk...
<snip>
... . it now seems unlikely that the
inner function is not being treated (correctly) ...

<snip>

The - not - in "not being treated" should not have been their. The final
paragraph should have read:-

The accessibility of the inner function by its identifier gave the
impression that Mozilla was treating the inner function as a function
declaration rather than as an expression. It now seems unlikely that
the inner function is being treated (correctly) as an expression but
that still leaves Mozilla a bit off spec on the scope chain ;-)

Richard.
Jul 20 '05 #10
Yep
"Richard Cornford" <Ri*****@litotes.demon.co.uk> wrote in message news:<bh*******************@news.demon.co.uk>...
When the function object is created by the evaluation of the function
expression the (optional) identifier is created as a property on a new
object added to the front of the current scope chain. That scope chain
is passed to the new function and the new Object is then removed from
the current scope chain. That means that the only scope that can resolve
the identifier for the function to a reference to the function object is
the scope within that function.


<snip excellent illustration />

I see what you mean, but ISTM that this is an ECMA inconsistency, and
as such I won't throw the stone to Mozilla guys for making such an
"exception" in not respecting the specs :-)

Check also the amusing
var foo = function bar(){ alert("Guess who I am");}
foo(); bar();
which is OK in IE but not in Mozilla and Opera for which "bar" is
undefined (now the behavior you're expecting is correct for Mozilla,
the identifier is really lost).

It's possible to check, however, that the identifier isn't really lost
and is indeed kept in the scope passed to the function. Check the
following in Mozilla:
var dw=function(s){document.write(s+"<br>")}
var foo = function bar(){
//foo.__parent__ is the local scope of foo
dw(foo.__parent__.bar) //now it's found!
dw(foo.__parent__.foo) //not found, foo is in global scope

//foo.__parent__.__parent__ is the global scope
dw(foo.__parent__.__parent__.foo); //found, OK
dw(foo.__parent__.__parent__.bar); //not found, "OK"
}
foo()
Cheers,
Yep.
Jul 20 '05 #11
> Check also the amusing
var foo = function bar(){ alert("Guess who I am");}
foo(); bar();
which is OK in IE but not in Mozilla and Opera for which "bar" is
undefined (now the behavior you're expecting is correct for Mozilla,
the identifier is really lost).


And check this out in IE:

<html><head><script>
var foo = function bar(){ alert(bar.ok);}
foo.ok = 'correct';
foo();
</script></head></html>

IE puts the function name in the wrong scope. It should go in the inner scope,
but instead is put in the outer scope.

http://www.crockford.com/javascript/private.html

Jul 20 '05 #12
Yep
"Douglas Crockford" <no****@laserlink.net> wrote in message news:<bh**********@sun-news.laserlink.net>...
And check this out in IE:

<html><head><script>
var foo = function bar(){ alert(bar.ok);}
foo.ok = 'correct';
foo();
</script></head></html>

IE puts the function name in the wrong scope. It should go in the inner scope,
but instead is put in the outer scope.


Actually IE seems to evaluate the "function bar" twice, the first time
as a function declaration, the second time as a function expression
(where it doesn't add the identifier to the inner scope chain - it
even does nothing with the identifier); as a result foo and bar aren't
even equal.

Add
bar.ok = "Hello?"
at the beginning of your script to have an illustration.
Regards,
Yep.
Jul 20 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Michael Winter | last post by:
In an attempt to answer another question in this group, I've had to resort to calling the DOM method, Node.removeChild(), using a reference to it (long story...). That is, passing Node.removeChild....
44
by: gregory.petrosyan | last post by:
Hello everybody! I have little problem: class A: def __init__(self, n): self.data = n def f(self, x = ????) print x All I want is to make self.data the default argument for self.f(). (I
3
by: Marc Llenas | last post by:
Hello all, I'm new to ASP.NET and I have a question regarding the fill method of a dataset. Here is my code 1 Dim objConn As OleDbConnection 2 Dim objAdapt As OleDbDataAdapter 3 Dim...
4
by: Daniel | last post by:
Hi, I was reading Douglas Crockford's article on prototypal inheritance at http://javascript.crockford.com/prototypal.html. I think it also relates to a post back in Dec 2005. The mechanism...
21
by: John Henry | last post by:
Hi list, I have a need to create class methods on the fly. For example, if I do: class Dummy: def __init__(self): exec '''def method_dynamic(self):\n\treturn self.method_static("it's...
30
by: HangEveryRepubliKKKan | last post by:
Ahahahaha.. Lets see if I get this Demented Lintard reasoning right. Vista is a failure becuase after 300 days after it's release, it only has 7.5% of the OS market while the Lintard OS, is a...
37
by: HangEveryRepubliKKKan | last post by:
"Jeremy Fisher" <freya@linux.serverwrote So much for LinTard Land. Here in the real world.... Microsoft profits up 23% this year over last. Ahahahahahahaha.... Vista is now eating away at...
14
by: Hendrik van Rooyen | last post by:
Hi, I am surprised that it took me so long to bloody my nose on this one. It must be well known - and I would like to find out how well known. So here is a CLOSED BOOK multiple choice...
0
by: Just_a_fan | last post by:
I am so happy about this I had to tell someone and since no one at the house even knows how to spell VB, I just had to make a short post. I finally got my little program to correctly do a second...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.