473,837 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determine object from property?

Is there a way to determine the object that a property is in? For
example:

function MyClass() { ... }
MyClass.prototy pe.myFunc = function() { ... }

var obj = new MyClass();
var sameobj = SOMEFUNCTION(ob j.myFunc);

So my goal is to get a reference to the object by just having the
property.

I think the answer is NO but I wanted to be sure there was not sime
built-in function that provided this.

Thanks,
-Mike

Sep 9 '05 #1
3 1710
mikeorb wrote:
Is there a way to determine the object that a property is in? For
example:
By "property", you mean "method" (or Function) in your example.
function MyClass() { ... }
MyClass.prototy pe.myFunc = function() { ... }

var obj = new MyClass();
var sameobj = SOMEFUNCTION(ob j.myFunc);
The example you give seems a little odd, in that you already have a
reference to "obj" in your variable name "obj", so why do you need a
function to get it again? Could you explain the application/context a
little more?
So my goal is to get a reference to the object by just having the
property.


For the purposes of this answer, I assume that you mean that if you
just pass a reference to "myFunc", can the receiving function guess
which instance of MyClass it came from. The answer is NO generally,
unless you use closures.

My answer is fairly amateur/simplified, so I hope it makes sense.

1 FUNCTIONS AS METHODS

In javascript, whenever you call a Javascript Function, it is always
being called as a "method" of some instance of an object.

You can discover which object is calling the function, through the
"this" keyword inside the function.

2 METHODS OF WINDOW OBJECT BY DEFAULT

The default is that a Function is called as a method of the "window"
object.

Thus:-

function MyFunction()
{
alert((this===w indow));
}

MyFunction(); // alerts true, "window" is implicit
window.MyFuncti on(); // explicit
window["MyFunction "](); // explicit

3. METHODS OF USER OBJECT

If you add a Function as a method of your own object, then the "this"
keyword will refer to the instance of that object, ONLY WHEN IT IS
CALLED AS A METHOD OF THAT OBJECT.

Thus:-

function MyClass(a)
{
this.a=a;
}
MyClass.prototy pe.myFunc=funct ion(){return this;};

function fTest()
{
var inst=new MyClass(1);
var sameinst=inst.m yFunc();
alert(sameinst. a);
}

However, if you get a reference to "myFunc" only, then "this" will
refer to the window object.

function fTest()
{
var inst=new MyClass(1);
var funcref=inst.my Func;
alert((funcref( )===window)); // true
}

4. CLOSURES

One way to achieve your goal may be to use closures. There are plenty
of posts in this news group on closures and scope chains if you search
it.

A closure is a means by which you can bind an externally declared
variable into a function. Effectively "global" variables are an
example of a closure at the top level of your script.

Thus:=

function MyClass(a)
{
var oInst=this; // oInst is effectively global to "myFunc"

this.a=a;

this.myFunc=fun ction(){
return oInst;
}
}

function fTest()
{
var inst=new MyClass(1);
var funcref=inst.my Func;
alert(funcref() .a);
}

Hope this helps.

Sep 9 '05 #2
"mikeorb" <mi*********@or b.dreamhost.com > writes:
Is there a way to determine the object that a property is in?
No.

There is no way to refer progammatically to a property, only to its
value[1], and that value can be a property of many objects.
var obj = new MyClass();
Insert
var otherObj = {myFunc: obj.myFunc};
var sameobj = SOMEFUNCTION(ob j.myFunc);
Then the value of "obj.myFunc " is a property of both "obj" and
"otherObj".
I think the answer is NO but I wanted to be sure there was not sime
built-in function that provided this.


There isn't.
/L
[1] Actually, an expression like "obj.myFunc " evaluates to a "Reference"
in the specification of ECMAScript, and a Reference does contain both
the object and the property. It is used for assigning the "this" value
when calling a method. There's just no way of getting to the object except
calling the method.
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 9 '05 #3
> The example you give seems a little odd, in that you already have a
reference to "obj" in your variable name "obj", so why do you need a
function to get it again? Could you explain the application/context a
little more?


I created a simple closure wrapper:

// Usage: var func = Method2Func(obj , method, [ static arguments to
method ]);
// func([dynamic arguments to method]);
//
// Example:
// var o = new MyClass();
// var hello = Method2Func(o, o.Hello, "static");
// hello("dynamic" ); // Invokes o.Hello("static ", "dynamic")
//
// Creates an anonymous function that, when called, invokes obj.func
and passes
// it the optional arguments you supply. There are two types of
arguments:
//
// 1) Static that are always passed. They are supplied in the
Method2Func
// call and are obviously evaluated when the function reference is
// created.
// 2) Dynamic arguments that are passed when you invoke the function.
These
// get appended to the static arguments.
function Method2Func(obj , func)
{
var static_args = [];
for (i = 2; i < arguments.lengt h; ++i)
{
static_args.pus h(arguments[i]);
}
return function()
{
var args = Array.concat(st atic_args, arguments);
func.apply(obj, args);
}
}

So I'd rather be able to say Method2Func(thi s.method) than
Method2Fun(this , this.method).

Oops. Uses this static method:

// Usage: var new_array = Array.concat(ar ray1, array2, ...)
Array.concat = function()
{
var array = [];
for (i = 0; i < arguments.lengt h; i++)
{
var sub_array = arguments[i];
for (j = 0; j < sub_array.lengt h; j++)
{
array.push(sub_ array[j]);
}
}
return array;
}

-Mike

Sep 9 '05 #4

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

Similar topics

10
1994
by: crjunk | last post by:
I have a script that I want to run only when my input box IS NOT disabled. Can someone tell me if something is wrong with my script? Is "disabled" the correct property to use? function TextChanged(i){ if (!document.ScheduleForm.disabled) { document.ScheduleForm.txtRecordStatus.value = "Changes Made; Record Not Saved."; document.ScheduleForm.txtRecordStatus.style.color = "#FF0000"; }
9
19541
by: Adam | last post by:
Can someone please help!! I am trying to figure out what a font is? Assume I am working with a fixed font say Courier 10 point font Question 1: What does this mean 10 point font Question 2: How do I determine how many characters I can get on a line Question 3: How do I determine how many lines I can get on a page. Assume no margins Question 4: Does their exist some kind of refernce table that will equate a font with chars/line and...
3
4442
by: BBFrost | last post by:
Ok, I know how to count the number of selected datagrid rows using the code below. What has me stumped is how to determine when the selected rows within a datagrid have been changed. The DataGrid object doesn't seem to have a any type of a selection changed type of event I can grab. THE QUESTION: Does anyone know how to determine when the selected row or set of rows within a datagrid has changed ??? This is driving me nuts !
2
3104
by: jmhmaine | last post by:
I've created a lookup class for a windows form application and I'm stuck on how on using the collection object. The process is simple, if the item is in the collection then return that object, if the item is not in the collection then create the item from a value in the database, then return it. Here is the code: Imports System.Data.SqlClient Public Class lookup
3
11592
by: Developer in California | last post by:
I am working on developing a generic Web framework using Master Pages in ASP.NET 2.0. What I have done is created a PageRenderer class which has a public method which will retrieve the path of the content I want to execute based on the name of the asp:Content control. As shown in the code snippet below, to get the content I want to display, I call the GetContentPagePath public method in PageRenderer passing a string duplicating the value...
3
1487
by: mrdylan | last post by:
Given a class like so: ------------------------------- class TestMe(object): def get(self): pass def set(self, v): pass p = property( get, set )
8
1708
by: Ole | last post by:
If I define a class and create a instant of it like e.g.: UserClass instantName = new UserClass(); how do I then determine the defined name "instantName" in the UserClass e.g. in a method (or a property) like this: public void userFunction() { string Var = new string();
7
16951
by: semedao | last post by:
Hi all, I view many posts about this issue , the connected property does not tell us the current status of the socket. based on couple of suggestions of msdn , and some article here , I try to write an helper method that will tell if the socket is connected or not , but it's not working good continue to tell me that the socket is connectedeven if the other party already call shutdown(both) + close , or , even if the other party close the...
2
7757
by: =?Utf-8?B?UmljaA==?= | last post by:
I have code to bold text in a datagridviewcell: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim cs As DataGridViewCellStyle, fnt As Font For Each c As DataGridViewCell In dgrv1.SelectedCells cs = c.Style Console.WriteLine(c.Style.Font) fnt = dgrv1.Font Console.WriteLine(fnt.Name)
0
10890
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...
0
10581
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10634
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
10279
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
9416
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...
1
7819
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4479
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
4053
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3127
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.