473,746 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function Context

Perhpas somebody can give me a hand with this little problem.

Given:

var object; -- an object
var func; -- a function call back

Now, I want to know how to get the following effect:

object.func = func;
object.func();

function func (somethingelse) {
this.something = somethingelse;
}

such that 'this' referes to 'object' without having to make 'func' a
member of 'object'. I tried `with (object) {func ();}` which I realized
wouldn't do that job.

Thanks,

Brett Foster
Jul 23 '05 #1
10 1610
On Fri, 07 Jan 2005 16:01:40 -0500, Brett Foster
<fo************ ****@ioctl.ca> wrote:

[snip]
object.func = func;
object.func();

function func (somethingelse) {
this.something = somethingelse;
}


func.call(objec t);

extending the call to include any arguments that the function, func,
should receive.

If this is for general Internet use (or for any environment that features
any JScript version earlier than 5.5 [which usually means IE5 or
earlier]), you should be prepared to emulate the call method:

if(Function.pro totype
&& ('function' != typeof Function.protot ype.call))
{
Function.protot ype.call = function(o) {var p = '__call', r;
while('undefine d' != typeof o[p]) {p += p;}
o[p] = this; r = o[p](); delete o[p]; return r;
};
}

If the object in question might be a host object (such as an element
reference), remove the while statement and delete operator (otherwise IE
will error) and don't use the same property name contained in the local
variable, p.

[snip]

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
Michael Winter wrote:
On Fri, 07 Jan 2005 16:01:40 -0500, Brett Foster
<fo************ ****@ioctl.ca> wrote:

[snip]
object.func = func;
object.func();

function func (somethingelse) {
this.something = somethingelse;
}
func.call(objec t);

extending the call to include any arguments that the function, func,

should receive.


OK, this is especially interesting in that I was about to ask a quite
similar question. However, I want to know how to use "call()" (or
apply()) from within an object constructor function.

Below is some code. In the second constructor, "FormExam", I'd like to
replace the existing line of code, with a call to either call() or
apply(), to acheive the same effect.

The example in Rhino, as I recall off the top of my head, says
"this.call(...) ", but this results in an error message that the method
is not defined. I've also tried FormExam.call(. ..) and
BaseFormExam.ca ll(....), but these too result in errors. What am I
doing wrong, or do I just need to leave it the way it is below (if it
ain't broke, don't fix it)?

Thanks in advance
function BaseFormExam(_f orm, _criteria) {
var criteria = _criteria;
var input = _form;

this._passes = function() {
//stub
return false;
}
}

function FormExam(_form, _criteria) {
this.base = BaseFormExam; this.base(_form , _criteria); delete
this.base;
}

Jul 23 '05 #3
On 7 Jan 2005 15:33:46 -0800, Got Scripting? <sc*******@yaho o.com> wrote:

[snip]

As a quick note, it's best to indent and manually wrap code.
function BaseFormExam(_f orm, _criteria) {
var criteria = _criteria;
var input = _form;
Why don't you use the arguments instead of creating local variables which
contain the same values. There would be no difference in behaviour.

[snip]
function FormExam(_form, _criteria) {
this.base = BaseFormExam; this.base(_form , _criteria);
delete this.base;
}


The same effect would be acheived with

function FormExam(_form, _criteria) {
BaseFormExam.ca ll(this, _form, _criteria);
}

This certainly works in browsers. I don't know about Rhino (assuming
that's your target environment).

Good luck,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4
Michael Winter wrote:
On 7 Jan 2005 15:33:46 -0800, Got Scripting? <sc*******@yaho o.com> wrote:
As a quick note, it's best to indent and manually wrap code.
um, my code simply lost its formatting when cutting and pasting into
google group's textarea (i'll have to keep this in mind for future
posts)
Why don't you use the arguments instead of creating local variables which contain the same values. There would be no difference in behaviour.
ok that's a good idea, see below
function FormExam(_form, _criteria) {
this.base = BaseFormExam; this.base(_form , _criteria);
delete this.base;
}


The same effect would be acheived with

function FormExam(_form, _criteria) {
BaseFormExam.ca ll(this, _form, _criteria);
}


in light of your "good idea" above, then I also decided to try:

BaseFormExam.ap ply(this, arguments);

since apply takes an array; worked like a charm. I also believe it's
Javascript 1.2 compliant?!
This certainly works in browsers. I don't know about Rhino (assuming that's your target environment).


Your example certainly did work. Sorry about the confusion. I meant
the Rhino book (Flanagan's "Javascript : The Definitive Guide"), rather
than the Rhino implementation.

Many thanks!!

Jul 23 '05 #5
On 7 Jan 2005 16:17:26 -0800, Got Scripting? <sc*******@yaho o.com> wrote:
Michael Winter wrote:
[snip]
function FormExam(_form, _criteria) {
BaseFormExam.ca ll(this, _form, _criteria);
}


in light of your "good idea" above, then I also decided to try:

BaseFormExam.ap ply(this, arguments);

since apply takes an array; worked like a charm. I also believe it's
Javascript 1.2 compliant?!


I don't have a Netscape reference to hand, but something like that.
However, Microsoft didn't implement it until JScript 5.5 (so usually IE5.5
or later). It might be easier to use the call method with the emulation I
showed earlier (though you'll have to modify it slightly to take - and to
use - arguments).
This certainly works in browsers. I don't know about Rhino (assuming
that's your target environment).


I meant the Rhino book (Flanagan's "Javascript : The Definitive Guide"),
rather than the Rhino implementation.


It's OK. I had Rhino (Moz) stuck in my head from an earlier thread. :)
Many thanks!!


You're welcome.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
Michael Winter wrote:
On 7 Jan 2005 16:17:26 -0800, Got Scripting? <sc*******@yaho o.com> wrote:
function FormExam(_form, _criteria) {
BaseFormExam.ca ll(this, _form, _criteria);
}
in light of your "good idea" above, then I also decided to try:

BaseFormExam.ap ply(this, arguments);

since apply takes an array; worked like a charm. I also believe it's Javascript 1.2 compliant?!


I don't have a Netscape reference to hand, but something like that.
However, Microsoft didn't implement it until JScript 5.5 (so usually

IE5.5 or later). It might be easier to use the call method with the emulation I showed earlier (though you'll have to modify it slightly to take - and to use - arguments).


Well this has certainly been enlightening. apply() seems the most
elegant for my particular usage, but the implementation limitations of
apply() and call() may just make me stick with my original:

this.base = BaseFormExam; this.base(_form , _criteria); delete
this.base;

Inelegant? Yes. But to me, simpler than hacking Function's prototype.
Though its still good to learn different approaches ;)

Jul 23 '05 #7
Michael Winter wrote:
<snip>
if(Function.pro totype
&& ('function' != typeof Function.protot ype.call))
{
Function.protot ype.call = function(o) {var p = '__call', r;
while('undefine d' != typeof o[p]) {p += p;}
o[p] = this; r = o[p](); delete o[p]; return r;
};
}

If the object in question might be a host object (such as an
element reference), remove the while statement and delete
operator (otherwise IE will error) and don't use the same
property name contained in the local variable, p.

<snip>

As I recall, the problem with IE's host objects is that they error on
the delete statement. I wonder whether assigning - Undefined - (the
current value of an unassigned local variable should do for that) would
be sufficient. In the event that the object did already have a property
name that coincided with (possibly repeated) '__call' then it would have
to be - Undefined - at the start of the execution of the - call -
emulation, and would be re-assigned - Undefined - at the end, which
should be (mostly) harmless.

Richard.

Jul 23 '05 #8
On Sat, 8 Jan 2005 12:31:12 -0000, Richard Cornford
<Ri*****@litote s.demon.co.uk> wrote:

[snip]
As I recall, the problem with IE's host objects is that they error on
the delete statement.


Yes, that's what I was trying to imply. Evidently Microsoft don't bother
with the internal attributes set forth in ECMA-262 and treat all
properties on host objects as DontDelete. Why they had to flag an error
rather than returning false is beyond me, though.

[alternative deletion suggestion]

if(Function.pro totype
&& ('function' != typeof Function.protot ype.call))
{
Function.protot ype.call = function(o) {var p = '__call', r, u;
while('undefine d' != typeof o[p]) {p += p;}
o[p] = this; r = o[p](); o[p] = u; return r;
};
}

An alternative to an uninitialised local variable would be void operator
which always evaluates to undefined.

This might be an odd question to ask, Richard, but am I checking for the
prototype object for any particular reason? I'm sure there *is* a reason -
and I'd assume that it's due to the provisions of ECMA-327 - but I've
completely forgotten. It's just become something I feel compelled to do.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9
Michael Winter wrote:
<snip>
This might be an odd question to ask, Richard, but am I
checking for the prototype object for any particular reason?
I'm sure there *is* a reason - and I'd assume that it's due
to the provisions of ECMA-327 - but I've completely forgotten.
It's just become something I feel compelled to do.

<snip>

It would take either a very odd, or extremely old, script implementation
for the Function.protot ype to be missing (and the old ones are so old
that you wouldn't have - typeof - to test with anyway). However,
verifying Function.protot ype doesn't seem a bad thing to be doing,
though logic would suggest verifying - Function - as well. It will
prevent the script from erring-out at the following test and is only
done once. Though if either Function or Function.protot ype were missing
then the script would likely error-out when call was later executed.

Richard.
Jul 23 '05 #10

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

Similar topics

3
14944
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
3
1858
by: jimjim | last post by:
Hello, My question concerns as to how a pointer is passed by reference as a function argument. The following is from code taken from the MICO implementation of the CORBA specification. in include files: typedef Context *Context_ptr; typedef ObjOut<Context> Context_out;
1
3979
by: Bryan Parkoff | last post by:
I know how to write "Pointer to Function" inside struct or class without using static, but I have decided to add static to all functions inside struct or class because I want member functions to be bound inside struct or class to become global functions. It makes easier for me to use "struct.memberfunction()" instead of "globalfunction()" when I have to use dot between struct and member function rather than global function. I do not have...
26
3130
by: Adam Warner | last post by:
Hello all, I'm very new to C but I have a number of years of Common Lisp programming experience. I'm trying to figure out ways of translating higher order concepts such as closures into C. The code will not be idiomatic C. GCC has an extension to ISO C that permits nested functions: <http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html> For implementing closures they have a serious limitation:
4
3625
by: anonymous | last post by:
Thanks your reply. The article I read is from www.hakin9.org/en/attachments/stackoverflow_en.pdf. And you're right. I don't know it very clearly. And that's why I want to understand it; for it's useful to help me to solve some basic problem which I may not perceive before. I appreciate your help, sincerely.
11
4733
by: Marco Loskamp | last post by:
Dear list, I'm trying to dynamically generate functions; it seems that what I really want is beyond C itself, but I'd like to be confirmed here. In the minimal example below, I'd like to create content to put at the address pointed to by f. In particular, I'd like to avoid/replace the memcpy line. Possible application (inspired by Paul Graham, "ANSI Common Lisp",
27
2487
by: Marlene Stebbins | last post by:
I am experimenting with function pointers. Unfortunately, my C book has nothing on function pointers as function parameters. I want to pass a pointer to ff() to f() with the result that f() prints the return value of ff(). The code below seems to work, but I would appreciate your comments. Have I got it right? Does the function name "decay" to a pointer? #include <stdio.h> /* declares a function which takes an argument that is a...
28
4333
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
4
2135
by: alex | last post by:
I am so confused with these three concept,who can explained it?thanks so much? e.g. var f= new Function("x", "y", "return x * y"); function f(x,y){ return x*y } var f=function(x,y){
6
7681
by: smmk25 | last post by:
Before I state the problem, I just want to let the readers know, I am knew to C++\CLI and interop so please forgive any newbie questions. I have a huge C library which I want to be able to use in a .NET application and thus am looking into writing a managed C++ wrapper for in vs2005. Furthermore, this library has many callback hooks which need to be implemented by the C++ wrapper. These callback functions are declared as "extern C...
0
8975
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
9516
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9286
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9219
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6062
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
4587
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
4840
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2768
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2200
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.