473,657 Members | 2,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Odd behavior involving function.apply( )

I've been working with the JavaScript Shell in Firefox on a
mad-scientist problem I've had in my head. Assume a function named
'object' that is designed to create an object based on a prototype
object -- the semantic is that the returned object prototypally
inherits from the argument 'o'.

function object(initiali zer, o) {
if (!o) o = Object;
function f() {}
f.prototype = o;
obj = new f();
obj.__progenito r = o;

if (initializer) {
if ((typeof(initia lizer)).toLower Case() != "function") throw
"Expected initializer to be of type function, got type " +
typeof(initiali zer);
initializer.app ly(obj);
}

return obj;
}

Now assume these uses of the object() function:

SimplePattern = object();

Prototype = object(
function() {
this.prototypeV alue = "Yo";
this.message = function(messag e) {alert(message) ;}
},
Object
);

Thing = object(
function() {
var secret = 42;
var _outer = this;

_outer.GiveUpSe cret = function() { return secret; }
},
Prototype
);

These all produce the results I would expect. Typical prototypal
inheritance.

But if I alter the Thing definition's initializer to include a member
that should inherit from Prototype,

Thing = object(
function() {
var secret = 42;
var _outer = this;

_outer.GiveUpSe cret = function() { return secret; }
_outer.subObjec t = object(
function initializer() {
var _inner = this;
_inner.subObjec tProp = 73;
},
Prototype
);
},
Prototype
);

Thing all of a sudden is -missing- its GiveUpSecret() function, has no
subObject member, and reports its prototypeValue as "Yo".

Why doesn't this work more intuitively?

--
Jeff S.

Jul 18 '06 #1
3 1394
Jeff Stewart wrote:
<snipped long, complicated test case>

Why doesn't this work more intuitively?
The best kind of irony is unintentional irony. That made me laugh out
loud :-)

As for your problem - your code looks like a scope quagmire to me.
Shouldn't you be assigning properties to your object rather than
creating them as local variables (as with "secret")? I don't fully
understand what you're trying to do - are you trying to create an
*object* that inherits from Prototype, or a new *type* that inherits
from Prototype?

Can you explain what you're trying to do? Maybe there's an analogous
pattern in a different language that you're trying to emulate? Whatever
it is, there is probably a simpler way.

Jeremy
Jul 19 '06 #2
The 'secret' is designed to illustrate that a hidden member could be
introduced into the created object using this pattern. It's based on
what I read on Crockford.com.

As for the intent, considering JavaScript really doesn't have "types",
I'm trying to create a new -object-. I'm obsessed lately with the idea
that JavaScript 1) was never designed to support classes (yet everyone
tries to force it to), 2) supports -prototypal- inheritance instead of
class-based inheritance, and 3) prototypes are -not- classes.

So the object() function is supposed to create either 1) objects with
an "instance" semantic attached to them, or 2) patterns -- prototypes
-- upon which other objects are based. But it should be composable --
again, the philosophy I'm adopting is that objects inherit from
prototypes, not classes/types. And, thusly, an object/instance created
from a prototype should be capable of acting as a prototype itself.

object() should be the root of this functionality: any source object,
by virtue of JavaScript, can be used as a prototype to create any other
object which can be said to "inherit" from the source object. I'm
trying to get back to basics amidst all the half-baked classical
inheritance implementations that do many things well but not the whole
thing with excellence. But though I'm getting back to basics, I still
want to try and introduce things like information hiding into the mix.

object() is a very hairy mutation of the function Crockford discusses
here: http://javascript.crockford.com/prototypal.html. I wasn't
satisfied with that method because it didn't support a more intuititve
initialization mechanism.

I had something I liked until I tried nested creation. In this
particular problem, I can't understand how the addition of one
property, subObject can so dramatically alter its owner object. I
thought I'd isolated all my execution contexts properly by latching
onto 'this' in all the right places using local variables, but somehow
the -nested- call to object() ended up modifying the object that
-owned- the call. How was that boundary violated?

As for it being a scope quagmire, well, in my defense, it -is-
JavaScript. Scope stopped being an easy concept when I was introduced
to the wild world of closures. :)

--
Jeff S.
Jeremy wrote:
Jeff Stewart wrote:
<snipped long, complicated test case>

Why doesn't this work more intuitively?

The best kind of irony is unintentional irony. That made me laugh out
loud :-)

As for your problem - your code looks like a scope quagmire to me.
Shouldn't you be assigning properties to your object rather than
creating them as local variables (as with "secret")? I don't fully
understand what you're trying to do - are you trying to create an
*object* that inherits from Prototype, or a new *type* that inherits
from Prototype?

Can you explain what you're trying to do? Maybe there's an analogous
pattern in a different language that you're trying to emulate? Whatever
it is, there is probably a simpler way.

Jeremy
Jul 19 '06 #3
Jeff Stewart wrote:
I've been working with the JavaScript Shell in Firefox on
a mad-scientist problem I've had in my head. Assume a
function named 'object' that is designed to create an
object based on a prototype object -- the semantic is that
the returned object prototypally inherits from the argument
'o'.

function object(initiali zer, o) {
if (!o) o = Object;
function f() {}
f.prototype = o;
obj = new f();
The variable - obj - has not been declared in this code and so will act
as a global variable. This is the root of your problem as when this
function is called recursively in your example the inner recursion
re-sets the global - obj - variable to the object it is creating during
the - apply - call, and so when that returns and the outer call then
returns - obj - it is the object created during the inner recursion that
is returned and assigned to the - Thing - variable.
obj.__progenito r = o;

if (initializer) {
if ((typeof(initia lizer)).toLower Case() != "function") throw
The - typeof - operator is clearly specified as returning the string
'function' when its operand is a javascript function. There is no need
to convert that string to lowercase for the comparison, and it is
probably dangerous to try to call apply on anything but a javascript
function so if - typeof - returned a mixed or uppercase version of
'function' then it would be a bad idea to then go on and call an apply
method on the object in question.
"Expected initializer to be of type function, got type " +
typeof(initiali zer);
initializer.app ly(obj);
}

return obj;
}

Now assume these uses of the object() function:

SimplePattern = object();

Prototype = object(
It cannot be a good idea to use the Identifier - Prototype - as if the
environment has/exposes an internal constructor for creating prototypes
that will likely be its name.

With the - obj - declared as a local variable, an actual object (- new
Object -) being passes into the function in place of - Object -, and
the - Prototype - Identifier changed to - PrototypeX -, the code
produces the results you seem to expect from it.

<snip>
Why doesn't this work more intuitively?
It is ridiculously convoluted, why do you expect it to be intuitive?

Richard.
Jul 19 '06 #4

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

Similar topics

1
2638
by: Thomas Brunko | last post by:
Hy, I'm working on a hash table and came upon a small problem. For a better explanation I've included an extract of the header file for the hash module: typedef struct TABLE * TABLE_P; typedef void* (*APPLY_SINGLE_F)( void * data ); typedef void* (*APPLY_PAIR_F)( void * key, void * value ); /* Allocate memory for the table and initialise it */ TABLE_P table_create();
1
1830
by: David Resnick | last post by:
I had a problem going from gcc 2.96 to gcc 3.2.3 and narrowed it down to the following code. The question is whether the problem is undefined behavior on the code's part or a compiler bug. #include <stdlib.h> #include <stdio.h> struct frob { char a; int b;
3
4567
by: Gene | last post by:
I'm not sure I understand this behavior (at least in the context of C#). I understand the use of "ref" and "out" keywords as they apply to method arguments, and then something this morning stopped me in my tracks. I must have used FileStream.Read a thousand times and it never dawned on me that I never have to specify either an "out" or "ref" when I pass the byte array that I pass to this function- yet it returns the bytes read from the...
3
1196
by: 63q2o4i02 | last post by:
Hi, I was wondering how I may get a python function to know what its name is without me having to write it manually? For example: def func1(): <do some stuff1> print 'func1' return True def func2(): <do some stuff2>
4
1956
by: comp.lang.tcl | last post by:
I wrote this PHP function in the hopes that it would properly use a TCL proc I wrote about 4 years ago: if (!function_exists('proper_case')) { /** * Ths function will convert a string into a proper case format using the customized TCL proc "PROPER_CASE" from the included TCL string tools libraries * * @access public
5
1668
by: lsolesen | last post by:
I used the following javascript to add confirm-boxes to links. The confirm-boxes are added at runtime for links with the class "delete". The script adds the function to the links. When I click the link, the confirm box i shown. But then it breaks; no matter if I press Cancel og Ok, there is the same behavior => the link is followed. I wonder why that is - off course I don't want to follow the link, if I select Cancel. var confirmboxes...
6
1290
by: cmdrrickhunter | last post by:
I'm getting rather inconsistent behavior with staticmethod. @staticmethod has the same problems, but I'm demonstrating it with staticmethod() because it shows things more clearly --------------------------------------------------- >>> class A: def orig(): print "hi" st = staticmethod(orig) st2 = st wrapped =
8
5521
by: Jon Harrop | last post by:
I am trying to learn C# and .NET programming in general but I am finding it very hard going. To start with, I'd like to translate some trivial functions from other languages that I am familiar with into C#. Here is a simple function in OCaml that nests "n" applications of "f" around "x", with "n" defaulting to "n=2": let rec nest ?(n=2) f x = if n=0 then x else nest ~n:(n-1) f (f x) For example, "nest f x" gives "f(f(x))" and "nest...
33
2823
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined. I am having some confusion with the former statement! Also, state the reason for the statement being undefined!
0
8394
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8306
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
7327
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4152
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.