473,574 Members | 2,639 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 3915

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
4670
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
7813
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, well explore What is ONU, What Is Router, ONU & Routers main...
1
7826
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...
0
8106
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...
1
5631
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...
0
5305
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...
0
3755
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2251
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
1
1350
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1066
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...

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.