473,729 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can I know if "new Func()" or "Func()" is called?

For example I wrote a function:
function Func()
{
// do something
}

we can call it like:
var obj = new Func(); // call it as a constructor
or
var result = Func(); // call it as a function

but, can i know if "new Func()" or "Func()" is called?

# sorry my english is not so good

Oct 9 '06 #1
37 3971

jh*****@gmail.c om написав:
For example I wrote a function:
function Func()
{
// do something
}

we can call it like:
var obj = new Func(); // call it as a constructor
or
var result = Func(); // call it as a function

but, can i know if "new Func()" or "Func()" is called?

# sorry my english is not so good
typeof(obj) always is "object", typeof(result) depends on result value
that Func() returns.
Sorry, my English also leaves much to be desired. :)

Oct 10 '06 #2
VK
How can I know if "new Func()" or "Func()" is called?

If a function is called as a constructor, it's running in the scope of
the newly created object, so [this] is pointing to the said object. If
it's called as a function, for top level functions [this] is set to
window object (talking about a regular script executed in a HTML
document) Thus in the most primitive form the check will be:

function Func() {
if (this == window) {
// called as function
}
else {
// called as constructor
// or (attention!) as method of an object
}
}

That's work reliable only to sort out cases of top-level constructors
called as regular functions. For more sophisticated cases you should
instruct your constructor in advance which [this] values it will
accept, say via internal variable in your constructor.

Oct 10 '06 #3
VK wrote:
How can I know if "new Func()" or "Func()" is called?

If a function is called as a constructor, it's running in the
scope of the newly created object,
The scope within a function is not influenced by how it is called.
There is no such thing as "the scope of a newly created object" (unless
the object is a function).
so [this] is pointing to the said object.
<snip>

The - this - value is not an aspect of a function's scope. The - this -
value and the applicable scope are characteristics of the execution
context.

Richard.

Oct 10 '06 #4
VK
If a function is called as a constructor, it's running in the
scope of the newly created object,

The scope within a function is not influenced by how it is called.
There is no such thing as "the scope of a newly created object" (unless
the object is a function).
Are you kidding or being *really* nitpicking? In case ifthe latter I'm
re-phrasing: "when called as a constructor, the function has the newly
created object instance at the top of the scope chain".

A new instance is created at the moment of execution "new SomeObject()"
statement. So it the moment SomeObject() function is called, a new
instance of SomeObject object is already created and placed at the top
of the scope chain so you could fill it with "this.somet hing =..." etc.
That should be clear that you are working with an instance of
SomeObject, not with a generic Object object. Thusly "this.somet hing
=..." etc. is an optional step, you can have a constructor as simple
as:
function SomeObject(){}
and then
var obj = new SomeObject();
which gives you an empty object just like new Object() *but* being an
instance of SomeObject (so its constructor is set properly, instanceof
will act properly and so on).

<html>
<head>
<title>Untitl ed Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function CustomObject() {
/* say we want this function to be used
* only as constructor, and not as a
* regular function
*/
window.alert(th is instanceof CustomObject);

if (this == self) {
throw new Error('Illegal constructor call');
}
else {
this.property1 = 'property1';
this.toString = CustomObject.to String;
}
}
// override toString to prevent source dump:
CustomObject.to String = function(){retu rn '';}

try {
var foo = new CustomObject();
window.alert(fo o.property1);

// noop:
var bar = CustomObject();
}
catch(e) {
window.alert(e. message);
}
</script>
</head>

<body>

</body>
</html>

Oct 10 '06 #5
VK wrote:
>>If a function is called as a constructor, it's running in the
scope of the newly created object,

The scope within a function is not influenced by how it is called.
There is no such thing as "the scope of a newly created object" (unless
the object is a function).

Are you kidding or being *really* nitpicking?
I am correcting your misapplication of technical terminology that has a
very precise (and important) meaning.
In case ifthe latter I'm re-phrasing: "when called as a constructor,
the function has the newly created object instance at the top of the
scope chain".
That is worse because instead of being an inappropriate use of the
terminology it is an absolutely false statement.

The execution context for a function call (including a function called
as a constructor) the object at the top of the scope chain is the
Activation/Variable object for that execution context. The object being
constructed does not appear on the scope chain for that execution
context at all (unless explicitly added using a - with - statement
within the constructor, and then it is not really the scope chain of
the execution context but the scope chain of the - with - statement. ).
A new instance is created at the moment of execution "new SomeObject()"
statement. So it the moment SomeObject() function is called, a new
instance of SomeObject object is already created and placed at the top
of the scope chain
When the process of calling the constructor gets to the internal
[[Call]] method of the function object a new instance of the Native
ECMAScript object has been created (and its [[Prototype]] property
set), but that object is *not* placed on the scope chain, it is
assigned to the - this - value.
so you could fill it with "this.somet hing =..." etc.
Nothing on the left of that assignment expression is resolved against
the scope chain.
That should be clear that you are working with an instance of
SomeObject, not with a generic Object object. Thusly "this.somet hing
=..." etc. is an optional step, you can have a constructor as simple
as:
function SomeObject(){}
and then
var obj = new SomeObject();
which gives you an empty object just like new Object() *but* being an
instance of SomeObject (so its constructor is set properly, instanceof
will act properly and so on).
<snip>

And that hangs on the assignment to the [[Prototype]] property of the
newly created object, and has nothing to do with scope chains at all.

Richard.

Oct 10 '06 #6
VK

Richard Cornford wrote:
The object being
constructed does not appear on the scope chain for that execution
context at all (unless explicitly added using a - with - statement
within the constructor, and then it is not really the scope chain of
the execution context but the scope chain of the - with - statement. ).
When the process of calling the constructor gets to the internal
[[Call]] method of the function object a new instance of the Native
ECMAScript object has been created (and its [[Prototype]] property
set), but that object is *not* placed on the scope chain, it is
assigned to the - this - value.
Is this what ECMAScript 3ed ed. mumbling? In such case I lost very
little by not reading it (except few paragraphs occasionally).

Let me explain how does it *really* work and ever worked on any UA with
javascript support, but first let me explain to you that [this]
statement points to the *current object*, thus to the object located at
the top of the scope chain. This way a statement like "object is *not*
placed on the scope chain, it is assigned to the - this - value" has no
programming sense whatsoever.

Now how does it *really* work:

var obj = new MyObject();

1) create an empty instance of MyObject object
2) call MyObject() constructor
2) place newly created instance at the top of the constructor scope
chain
3) execute MyObject() statements (if any)
4) if there is no [return] statement in the constructor, then return
the newly created instance of MyObject object (equivalent of "return
this;")
If there is [return] statement in the constructor and it is not "return
this;", then return whatever pointed by this statement. The newly
created instance of MyObject object - unless it was referenced
somewhere else in the constructor - will remain dereferenced and soon
removed by Garbage Collector.

The above can be discussed for better wording, but any source stating a
different *schema* is a junk to disregard: in application to any UA.

Oct 10 '06 #7
VK wrote:
Let me explain how does it *really* work and ever worked on any UA
with javascript support
You're wrong. Can't you even test your own theories by typing a few lines of
code?
>, but first let me explain to you that [this]
statement points to the *current object*, thus to the object located
at the top of the scope chain. This way a statement like "object is
*not* placed on the scope chain, it is assigned to the - this -
value" has no programming sense whatsoever.
If your statements were true, then this code:

function Obj() {
this.value="xyz ";
alert(value);
}
var x = new Obj();

should alert "xyz". Since according to you, "this" is put into the scope
chain.

However, it doesn't. It causes an error because 'value' is undefined.
How can you explain this BAFFLING behavior?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 10 '06 #8
VK
You're wrong. Can't you even test your own theories by typing a few lines of
code?
That is not a theory: that is a well-known fact used in thousands of
lines of code I typed. The OP question was " how can I know if "new
Func()" or "Func()" is called?". That was answered by using *my*
knowledge of JavaScript mechanics. If you see my solution doesn't work,
then point the error so OP would get a better answer. If you don't like
my answer just because "if cannot work because it cannot work this way
- even it works" when it's not my problem.
If your statements were true, then this code:

function Obj() {
this.value="xyz ";
alert(value);
}
var x = new Obj();

should alert "xyz". Since according to you, "this" is put into the scope
chain.

However, it doesn't. It causes an error because 'value' is undefined.
How can you explain this BAFFLING behavior?
That's easy, but first let's us close the question of the the real
constructor mechanics (if anyone still have some doubts):

<script type="text/javascript">
function MyObject() {
window.alert(th is instanceof MyObject);
window.alert(th is.constructor == Object.construc tor);
window.alert(th is.prototype == Object.prototyp e);
}

var obj = new MyObject();
</script>

- watch what is true and what is not.

Now about your case: that is not a "baffling" behavior but a very well
thought machanics for object constructors in javascript: which doesn't
have neither default object accessor shortcut (like VB) nor formal
members declarations like say Java. That would be a holy mess then in
cases like:

function MyObject(width, height) {
this.width = width;
this.height = height;
}
//what to assign to what?

So the default object pointer (and this is what [this] is) is acting a
bit differently in the context of a constructor call. Does it affect to
OP's problem?

Oct 10 '06 #9
jh*****@gmail.c om wrote:
but, can i know if "new Func()" or "Func()" is called?
This should work:

function asConstructor(t hat)
{
return that instanceof arguments.calle e.caller
}

function f()
{
alert(asConstru ctor(this))
}

var obj = new f(); // ==true
f(); // ==false

Oct 10 '06 #10

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

Similar topics

6
4698
by: kelvlam | last post by:
Hello, I'm a new begininer with JavaScript. I'm trying to figure out which is the best approach, and to understand the differences between them. I have a <Aelement that's suppose to either launch a popup window, or it will link you to some dynamic created page. I have declared a global JavaScript function
0
9426
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
9200
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
9142
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...
1
6722
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...
0
6022
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
4525
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
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
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
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.