473,396 Members | 1,760 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 3882

jh*****@gmail.com написав:
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.something =..." etc.
That should be clear that you are working with an instance of
SomeObject, not with a generic Object object. Thusly "this.something
=..." 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>Untitled 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(this instanceof CustomObject);

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

try {
var foo = new CustomObject();
window.alert(foo.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.something =..." 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.something
=..." 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(this instanceof MyObject);
window.alert(this.constructor == Object.constructor);
window.alert(this.prototype == Object.prototype);
}

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.com wrote:
but, can i know if "new Func()" or "Func()" is called?
This should work:

function asConstructor(that)
{
return that instanceof arguments.callee.caller
}

function f()
{
alert(asConstructor(this))
}

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

Oct 10 '06 #10

Matt Kruse wrote:
You're wrong. Can't you even test your own theories by typing a few lines of
code?
It's _VK_. We have Luigi, you have VK. Couldn't beat a clue into
either of them with a hammer.

Oct 10 '06 #11
VK wrote:
>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.
It is not a fact. It is another of your fictions. It is likely that you
have "used" in thousands of likes of your code, but then you don't
actually know what the code you write does or how it 'works'. Hence all
the mystical incantations you use.
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.
Not particularly well answered. A more reasonable test would be to
compare the constructor function with the constructor property of the
object, but even that would not preclude the constructor being called as
a method of one of its instances, or another object with its constructor
property explicitly modified.

But a better answer would be to question who is likely to be calling a
constructor as a function, and the benefits of knowing that someone is
programming stupidly rather than letting them cope with the errors that
should be expected to follow from their incompetence.
If you see my solution doesn't work, then point
the error so OP would get a better answer.
And if we see you bullshitting the OP shouldn't we point that out as
well? Remember than anyone who believes your nonsense effectively knows
less as a result than they would if they knew nothing.
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.
You are making statements that are false. That is a reasonable thing for
people to object to, and point out.
>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,
Is it? So why didn't you explain it? That question is, of course,
rhetorical, as you have made it very clear that you don't comprehend the
role of Identifier resolution in javascript so you don't know that Matt
is demonstrating your statement false, or how he is doing so.
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(this instanceof MyObject);
window.alert(this.constructor == Object.constructor);
window.alert(this.prototype == Object.prototype);
}

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

- watch what is true and what is not.
What possible relevance does any of that have?
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:
What javascript does have is lexical scopeing, where an Identifier is
resolved against the scope chain. So in Matt's example the - value -
Identifier is resolved against the scope chain, and so if any object on
the scope chain has a property (or the prototype of any object on the
scope chain had a property) named 'value' The Identifier would be
resolved as the 'value' property of that object.

That is how Matt's code demonstrates that the object being constructed is
not placed on the scope chain. If it were then the - value - Identifier
would be resolved and there would be no error.

You assertion that the object is placed at the top of the scope chain is
demonstrably false. And it has been demonstrated false. But let's do so
again; we know that the - with - statement places an object at the top of
the scope chain for the duration of the execution of its (possibly Block)
statement. Thus we can examine what code does when there is an object
with the - value - property at the top of the scope chain:-

var obj = {value:'xx'};

with(obj){
alert(value);
}

And that does not produce an error, because there is an object at the top
of the scope chain with a - value - property.
function MyObject(width, height) {
this.width = width;
this.height = height;
}
//what to assign to what?
The formal parameters are resolved against the scope chain, and the
property accessors are resolved first as references the - this - object
(whatever it is in the execution context in question) and then the right
hand side of the dot operator as properties of that object. There is no
ambiguity.
So the default object pointer (and this is what [this] is)
is acting a bit differently in the context of a
constructor call.
The value of the - this - keyword is determined entirely by how the
function is called, as always.
Does it affect
to OP's problem?
Probably not, but it does not explain why the symptoms that would follow
from the - this - object being at the top of the scope chain (or indeed,
on the scope chain at all) are not manifest in reality. The best
execution of that is that your assertion that the - this - object is
added to the top of the scope chain during the execution of a constructor
is utterly false; another fictional product of your deranged imagination,
and something the wider world would be better off without.

Ricahrd.
Oct 10 '06 #12
VK wrote:
Richard Cornford wrote:
>The object being constructed does not appear on the scope
chain for that execution context at all ( ... ). 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?
Yes, it is how javascript is specified as behaving, and how implications
actually do behave.
In such case I lost very little by not reading it
it seems unlikely that you would comprehend the specification if you did
read it, as you have no talent for technical subjects and don't
comprehend logic to the degree necessary for programming.
(except few paragraphs occasionally).
Which his evident in the jargon you borrow from the specification, and
then miss apply to the general confusion of anyone reading your rubbish.
Let me explain how does it *really* work
That is not possible for you, as you have no idea yourself.
and ever worked on any UA with javascript support,
Or, never worked on any UA.
but first let me explain to you that [this]
statement points to the *current object*,
The - this - keyword refers to the - this - object. There is no sense in
which an object is "current" except its being the - this - object.
thus to the object located
at the top of the scope chain.
Absolutely not! the scope chain is a very specific structure and is used
in a very specific way in order to resolve Identifiers. In a constructor
the - this - object is not on the scope chain, and when a function is
called as a method the - this - object is normally not on 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 a statement that is absolutely true has "no programming sense" to you
then the fault is yours.
Now how does it *really* work:

var obj = new MyObject();

1) create an empty instance of MyObject object

No, it creates an instance of the Native ECMAScript object and assigns
the value of the - prototype - property of the constructor to the
internal [[Prototype]] property of that object.
2) call MyObject() constructor
You have omitted passing a reference to the new native ECMAScript object
to the function call as the - this - object.

But why do you have two items labelled "2" here?
2) place newly created instance at the top of the
constructor scope chain
That never happens (so you can never validly demonstrate that it does, as
is always the case with a false statement).
3) execute MyObject() statements (if any)
That certainly does happen (though most of the code you place in
constructors has no business being there).
4) if there is no [return] statement in the constructor,
then return the newly created instance of MyObject object
(equivalent of "return this;")
This is true.
If there is [return] statement in the constructor and
it is not "return this;", then return whatever pointed
by this statement.
<snip>

That is false. Your believing this explains why you put - return null; -
statements in constructors you write, but you have already been told that
doing so is worthless and does no more than demonstrate your
incompetence.

<snip>
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.
The above contains two statements that are absolute factually false (and
demonstrably so), yet you think that anyone (or anything) saying so is
"junk to be disregard"? It is that attitude that leaves you labouring
under fictional reception of javascript, and writing code that doesn't do
you think it does, and not being able to see that as the case.

Richard.
Oct 10 '06 #13
ru****@gmail.com wrote:
jh*****@gmail.com wrote:
>but, can i know if "new Func()" or "Func()" is called?

This should work:

function asConstructor(that)
{
return that instanceof arguments.callee.caller
}

function f()
{
alert(asConstructor(this))
}
<snip>

Only in implementations that provide the non-standard - caller -
property, and as a property of the function object. In other
implementations it will error-out.

Richard.
Oct 10 '06 #14
VK
your assertion that the - this - object is
added to the top of the scope chain during the execution of a constructor
is utterly false;
OK, break!
I just hate these Books of ECMA liturgies, they affect me like a red
color on a bull :-) I did a false statement about [this] nature (which
is a pointer to the current object, not to the default object). You did
false statements about that is [this] pointing to in the constructor
and about return values in the constructor. So let's it put all
together once again:

If some function is called as an object constructor
var obj = new MyObject();
its (constructor's) current object is set to the newly created empty
instance of MyObject object.
My error: calling "current object" as "default object".
Your error: calling empty instance of MyObject object as "empty
instance of the default Object object".
<note>
That is not really your error: just another side effect of taking
ECMAScript specs as a *language specs* while it is *engine specs*. The
danger of it is that you can easily miss the level of the language
itself and fell through to the lower-level processes making the engine
to work. It is dangerous because lower of a certain level the
differences between different languages disappear: so you'll ending up
by stating generic language engine mechanics instead of
JavaScript-particular facts. Of course initially a generic Object
object instance is created and then patched by oid's, constructor
references, then floating from constructor to constructor to get its
"flash" (object members). But it is true for JavaScript as well as for
Java or C++: you're missed the level of JavaScript specifics, go up!
:-)
</note>

In the constructor you can assign members to this newly created
MyObject instance or just leave it empty. The latter has not too much
of practical sense, I just want to remind once again that
"this.property = something" inside a constructor is an optional step,
it doesn't make any "instantiation magic".

If there is no [return] statement inside the constructor, it returns
the newly created MyObject instance reference (equivalent of - return
this; - statement).
If there is a return statement inside the constructor, it returns
whatever the return statement points to. If it is not - return this -
and if we did not store a reference to the newly created instance
somewhere else in the constructor: in this case the newly created
MyObject instance will remain dereferenced and soon removed by the
Garbage Collector. The latter means that we can call a function as a
constructor and change our mind right during the process. Practical
importance if it is in an ability to have singletons in JavaScript.
Your error: saying that return value has no effect for a constructor
and that say - return null; - inside a constructor has no effect.

A small sample to illustrate your latter mistake:
<script type="text/javascript">
function MyFriendlySingleton() {
if ((this instanceof MyFriendlySingleton) != true) {
return null;
}
else if (MyFriendlySingleton.$_$) {
return MyFriendlySingleton.$_$;
}
else {
MyFriendlySingleton.$_$ = this;
this.property = 'foobar';
}
}

var obj1 = new MyFriendlySingleton();
var obj2 = new MyFriendlySingleton();
var obj3 = MyFriendlySingleton();

window.alert(obj1 === obj2);
window.alert(obj3 === null);
</script>

Overall I see it as a valuable experience exchange (I learned the right
term to use for [this], you've learned how does a function-constructor
really work in *JavaScript* - not in ECMAScript specs).

Now concerning practical needs to distinguish between Func() and new
Func() calls inside Func() itself (that is what OP wanted).
I cannot comment on OP's real needs as he did not tell us about it. In
my code it is often useful to monitor [this] nature in the classy
inheritance emulation. As I said earlier, that is not a real hardcoded
super-extends inheritance, so say in case like:
function ObjectOne() {
// ...
}
function ObjectTwo() {
ObjectOne.call(this);
// ...
}

ObjectOne.call(this) doesn't create inheritance relationship between
ObjectOne and ObjectTwo, so it is not a super() call but merely its
close functional equivalent.
That means that anyone can create ObjectThree with ObjectOne.call(this)
statement, other words anyone can parasite on my construction chain
with her own constructors. Most of the time it doesn't bother me:
overall any attempts to create a "robust" execution context protection
in a runtime compiled language are futile, that can be only some level
of "obfuscation". Yet sometimes I want to have if not a "bulletproof
block" for my construction chain then at least some kind of protection.
In such case studying the nature of the current object (this) is very
helpful.

<script type="text/javascript">
function Dell(oid) {
if (oid != 'Dell123454321') {
throw new Error('Illegal constructor call');
}
// a few static fields:
this.producer = 'Dell, Inc.';
this.URL = 'http://www.dell.com';
// a few static methods:
this.showConfig = Dell.showConfig;
this.toString = Dell.toString;
}

Dell.showConfig = function() {
window.alert(
this.producer + '\n'
+ this.URL + '\n\n'
+ this.RAM + ', '
+ this.processor);
}
// We do not change the Function prototype
// itself to keep the "minimum necessary
// change" principle: for other functions
// toString should remain the default one.
Dell.toString = function(){return '';}

function OptiFlex(RAM, processor) {
if (!this instanceof OptiFlex) {
throw new Error('Illegal constructor call');
}
Dell.call(this, 'Dell123454321');
this.RAM = RAM || '256Mb';
this.processor = processor || 'Intel 1.2GHz';
}
OptiFlex.toString = function(){return '';}

var myComputer = new OptiFlex(null, 'Athlon 1.7 GHz');
myComputer.showConfig();
</script>

Yes, it is not the CC scope management you are using, it is another
approach. I like it better for the simplicity and extendibility, but
it's my strictly private opinion. CC has just too many parenthesis of
all kinds for my blood: by the moment of putting the Nth pair I don't
remember anymore that is the first doing here. :-) You are free to sign
it it off to the limitations of my humble mind.

Oct 11 '06 #15
VK wrote:
I just hate these Books of ECMA liturgies, they affect me like a red
color on a bull :-)
[snipped everything else, as I stopped reading here]
Bulls are actually color blind.
The breadth of your ignorance is astounding.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 11 '06 #16
VK

Matt Kruse wrote:
Bulls are actually color blind.
The breadth of your ignorance is astounding.
After humbly suggesting to go f*** yourself, Sir (and start learning
JavaScript instead of ECMAScript):

I gave an answer to OP question, and later went on a straw-man trick so
I called "current object" as "default object". That is maybe a huge
crime by your scale: but by my scale it has no comparison to the amount
of b.s. posted in this thread by other people in relevance to function
constructors. The statement alone that "returning null from a
constructor has no effect" demostrates such shiny lack of a real
javascript programming experience that I could call [this] as "foobar
property of foobarer" and I would still remain in big plus by any
"error-meter".

Oct 11 '06 #17
VK wrote:
>your assertion that the - this - object is added to the top of the
scope chain during the execution of a constructor is utterly false;

OK, break!
I just hate these Books of ECMA liturgies,
And look where that gets you.
they affect me like a red color on a bull :-)
I did a false statement about [this] nature (which
is a pointer to the current object, not to the default object).
As neither a technical terms in javascript that was not a false
statement, only a statement that was too vague to mean anything useful.

The primary false statement under discussion here has been your
assertion that in a constructor the newly created object is added to
the scope chain. The scope chain being a well defined structure with a
precisely specified role in the resolution of Identifiers in
javascript, and so if it had been true your assertion that the newly
created object was added to the scope chain would have significant
implications. It would also have been an assertion that was
demonstrable. However, Matt and I have demonstrated that the newly
created object cannot be added to the scope chain by showing that the
effect on Identifier resolution that would follow from that action is
not present in javascript.
You did false statements about that is [this] pointing to in the
constructor
Did I? You cannot cite one from any of my previous posts in this
thread.
and about return values in the constructor.
No, I was correct in what I wrote.
So let's it put all
together once again:
You mean you want to have yet another go at expounding your
misconceptions.
If some function is called as an object constructor
var obj = new MyObject();
its (constructor's) current object is set to the newly created empty
instance of MyObject object.
There is no such thing as an "empty instance of MyObject", beyond there
being a native ECMAScritp obejct with its internal [[Prototype]]
property referring to the value of - myOjbect.prototype - at the time.
My error: calling "current object" as "default object".
The object is neither "current" nor "default". It is just the object
that results from the use of the - new - operator on a function
reference.
Your error: calling empty instance of MyObject object as "empty
instance of the default Object object".
I did not call it an empty instance of the default object. I called it
an instance of the native ECMAScript object (the only object type in
javascript) with its [[Prototype]] property set to the - prototype - of
the constructor.

There is no sense in "default Object" in a language where there is only
one object type.
<note>
That is not really your error: just another side effect of taking
ECMAScript specs as a *language specs*
To you it may be a mistake to take a language specification as a
language specification, others know better.
while it is *engine specs*.
If there is one thing ECMA 262 does not do it is specify how the
language is to be implemented.
The danger of it is that you can easily miss the level of the
language itself and fell through to the lower-level processes
making the engine to work.
Gibberish!
It is dangerous because lower of a certain level the differences
between different languages disappear: so you'll ending up
by stating generic language engine mechanics instead of
JavaScript-particular facts.
Your notion of "JavaScript particular facts" doesn't even agree with
reality.
Of course initially a generic Object object instance is created and
then patched by oid's, constructor references, then floating from
constructor to constructor to get its "flash" (object members).
More gibberish!
But it is true for JavaScript as well as for Java or C++: you're
missed the level of JavaScript specifics, go up!
:-)
You mean I know how javascript works to the extent of being in a
position to precisely predict how code will execute, while you cannot
even tell when the code you write actual does work or not (and
certainly could not explain how or why it odes what it does) and I am
the one who is missing something?
</note>

In the constructor you can assign members to this newly
created MyObject instance or just leave it empty. The latter
has not too much of practical sense,
It is manifest in your code that you have not yet perceived the role of
the constructor's prototype.
I just want to remind once again that
"this.property = something" inside a constructor is an optional step,
it doesn't make any "instantiation magic".
There is no need for you to worry about others adopting mystical
beliefs out of thin air, that is a failing that follows form your
insanity and not something that should be expected of the rational.

Now, what happened to your assertion about adding the newly created
object to the scope chain? Are you conceding that it was (as I stated)
utterly false by omitting that step from this 'description'?
If there is no [return] statement inside the constructor,
it returns the newly created MyObject instance reference
(equivalent of - return this; - statement). If there is a return
statement inside the constructor, it returns whatever the
return statement points to.
Once again, nonsense. The behaviour of return statements in functions
called as constructors is fully specified and the rule is; If the
function explicitly returns an object then the result of the - new
FucntionRef - expression is that object, else it is the newly created
object.

The - null - value is not an object in javascript so a - return null; -
statement in a function that is called as a constructor will not result
in a null value. Try it:-

function AnObject(){
return null;
}
AnObject.prototype.testValue = 'XXX';

var obj = new AnObject();

alert(obj.testValue);

- which alerts 'XXX' rather than erroring, which is what it would do if
the - new AnObject() - expression returned null.

One of the advantages of reading the language specification is that in
doing so you can learn the rules that actually do apply in situations,
including the use of return statements inside constructors. And those
rules are usually a lot les complex than the web of fictions that
represent your understanding of javascript.
If it is not - return this - and if we did not store a reference to the
newly created instance somewhere else in the constructor: in this
case the newly created MyObject instance will remain dereferenced
and soon removed by the Garbage Collector. The latter means that
we can call a function as a constructor and change our mind right
during the process. Practical importance if it is in an ability to
have singletons in JavaScript. Your error: saying that return value
has no effect for a constructor and that say - return null; - inside
a constructor has no effect.
Was that my error? The evidence says otherwise.
A small sample to illustrate your latter mistake:
<script type="text/javascript">
function MyFriendlySingleton() {
if ((this instanceof MyFriendlySingleton) != true) {
return null;
}
else if (MyFriendlySingleton.$_$) {
return MyFriendlySingleton.$_$;
}
else {
MyFriendlySingleton.$_$ = this;
this.property = 'foobar';
}
}

var obj1 = new MyFriendlySingleton();
var obj2 = new MyFriendlySingleton();
var obj3 = MyFriendlySingleton();

window.alert(obj1 === obj2);
window.alert(obj3 === null);
</script>
It is no wonder you struggle to understand the simplest concepts. Here
you have attempted to 'demonstrate' something with an overly complex
mass of code, when an absolutely simple case would have proved you
wrong, and you have failed to do the one thing that is significant to
the question; return null from a function called as a constructor. In
fact you have tried to arranged that you function only returns null
when it is _not_ called as a constructor, which demonstrated nothing
significant as the return values from functions not called as
constructors are the value returned (and absolutely expected to be so).
Overall I see it as a valuable experience exchange
The only valuable lesson you could learn is a proper appreciation of
how very little you understand about javascript and computer
programming. Learning that lesson is the only thing that will stop you
from being a worthless waste of time.
(I learned the right term to use for [this],
Apparently not.
you've learned how does a function-constructor
really work in *JavaScript* - not in ECMAScript specs).
No, I learned that half a decade ago, and you probably don't understand
it even now I have explained the actual rule.
Now concerning practical needs to distinguish between Func() and
new Func() calls inside Func() itself (that is what OP wanted).
Ah, now we have the opinion of the worst programmer I know of.
I cannot comment on OP's real needs as he did not tell us
about it.
Yet you feel yourself able to tell him how he should be approaching his
problem, even though he has not explained what his problem actually is.
And recommended a semi-functional scripted hack where something as
simple as a common naming convention could answer the situation
satisfactorily. (That is; it is common to use initial uppercase
characters on the names of functions intended to be used as
constructors so anyone calling a function with an initial uppercase
character directly should be expecting problems, or be called
incompetent, as should anyone designing functions to be called directly
and used as constructors).
In my code it is often useful to monitor [this] nature in the classy
inheritance emulation.
As you do not have a clue as to what to expect from javascript (being
utterly ignorant of the technicalities of the language) it does not
surprise me that you fell you have that need. On the other hand
computer programmers will not have the same experience.

<snip: irrelevant nonsense code, etc.>
Yes, it is not the CC scope management you are using,
You don't know what you are talking about (and as you are making your
own terminology up off the top of your head again it is unlikely that
many others will either).
it is another approach. I like it better for the simplicity and
extendibility, but it's my strictly private opinion.
You have just posed a mass of needlessly complex code and you consider
it represents "simplicity"? In javascript the simple approach to
'classes' and class hierarchies is through assigning objects to the
prototypes of constructors, or modifying the prototypes that start
with.

An approach that gets as far as using the - call - or - apply - methods
is already two or three steps into complex elaboration. You use such an
approach because you don't understand javascript well enough to see the
simplicity where it is, and instead just regurgitate an approach that
you were shown once and that 'works', regardless of the fact that it is
inappropriately complex for the simple applications you use it with.

The point of actually understanding javascript is to be able to see the
approach most applicable to a situation. And so be able to write code
that is precisely no more complex than it needs to be. What you label
"CC" is more complex than is suitable for the vast majority of cases
(though not as complex as you perceive it, but that it because it
requires a real technical understanding of the langue in order to work
with, not the mush of misconceptions and fictions you attempt to
perceive it with), but what you are doing is also fat too complex for
the majority of cases.
... You are free to sign it it off to the limitations of my humble mind.
Personal insanity is still the explanation of your posts that most
closely fits the facts.

Richard.

Oct 11 '06 #18
jh*****@gmail.com wrote:
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
How about this:

function TestConstructor()
{
if(this.constructor == TestConstructor)
alert("New Object");
else
alert("Function Call");
}

Jeremy
Oct 11 '06 #19
Jeremy wrote:
How about this:

function TestConstructor()
{
if(this.constructor == TestConstructor)
alert("New Object");
else
alert("Function Call");
}

Jeremy
good and simple.

Oct 11 '06 #20
VK wrote:
Matt Kruse wrote:
[snip]
>The breadth of your ignorance is astounding.

After humbly suggesting to go f*** yourself, Sir ...
You would do Usenet at large a favour if you took your own advice.
(and start learning JavaScript instead of ECMAScript):
Still living in a private world where JavaScript isn't an implementation
of ECMAScript, eh?
I gave an answer to OP question,
And, as usual, it was a bad one. The constructor isn't "running in the
scope of the newly created object", and whether a function is "top
level" or not is irrelevant with regard to which object is referenced by
the this operator.
and later went on a straw-man trick so I called "current object" as
"default object".
Both are meaningless, anyway.
That is maybe a huge crime by your scale:
The incorrect use of terminology is not a huge crime, no, but unless it
was by accident, knowledge and understanding wouldn't permit such a mistake.
but by my scale it has no comparison to the amount of b.s. posted in
this thread by other people in relevance to function constructors.
Other people? LMFAO!
The statement alone that "returning null from a constructor has no
effect" demostrates such shiny lack of a real javascript programming
experience ...
Really? So what do you expect:

function MyObject() {
this.member = 'value';

return null;
}

var object = new MyObject();

to do? Return null? Raise an exception? Return an object but omit the
property? Shame it doesn't do any of those things: it returns the object
as if the return statement wasn't even there. Even if you only tested in
Fx or IE, you would have found that out for yourself.

Will you ever learn?

Mike
Oct 11 '06 #21
runsun pan wrote:
Jeremy wrote:
>How about this:

function TestConstructor()
{
if(this.constructor == TestConstructor)
alert("New Object");
else
alert("Function Call");
}

Jeremy

good and simple.
But still not reliable:-

var obj1 = new TestConstructor();

var obj2 = TestConstructor.call(obj1); // <- no - new - operator.

will alert "New Object" twice, when the second call is not as a
constructor. Also:-

var obj1 = new TestConstructor();

obj1.method = TestConstructor;

var obj2 = obj1.method();

- again will alert "New Object" twice when the second call to -
TestConstructor - is as a method not a constructor.

The odds are good that the actual problem that the OP is attempting to
address does not really require a reliable solution, but as we have seen
there are numerous possibilities, of more or less complexity and with
differing reliabilities and compatibilities. Until the OP answers the
question 'why?' knowing which would best address the issue is not
possible.

Richard.
Oct 11 '06 #22
Richard Cornford wrote:
>
But still not reliable:-

var obj1 = new TestConstructor();

var obj2 = TestConstructor.call(obj1); // <- no - new - operator.

will alert "New Object" twice, when the second call is not as a
constructor. Also:-

var obj1 = new TestConstructor();

obj1.method = TestConstructor;

var obj2 = obj1.method();

- again will alert "New Object" twice when the second call to -
TestConstructor - is as a method not a constructor.

The odds are good that the actual problem that the OP is attempting to
address does not really require a reliable solution, but as we have seen
there are numerous possibilities, of more or less complexity and with
differing reliabilities and compatibilities. Until the OP answers the
question 'why?' knowing which would best address the issue is not
possible.

Richard.

Interesting. Can't think of a way to fix those scenarios without adding
extraneous properties to the object, so I guess you're right.

I also have never had to use function.call() in my entire life, and I
can't see any reason why you would want to attach a constructor as a
method to another object.

Then, I can't really see why it would ever be desirable to call a
constructor as a regular function. Seems like asking for trouble, IMHO.
I agree that the OP should explicate his or her reasoning.

If you have functionality that you want to use both in the constructor
and as a normal function, why not remove that functionality and
encapsulate it in a separate function apart from the constructor?

Jeremy
Oct 11 '06 #23
VK
You would do Usenet at large a favour if you took your own advice.

I'm mostly very respectful to the netiquette, and I definitely do not
attack anyone just out of sport. But over the last year and half I'm
getting a bit fed up by very few but highly noisy people in c.l.j. That
must be an age change or a work stress, but I'm getting no more
strength to smile on it. So you are getting the same advise I just gave
to another person (avoiding to retype, just scroll up). You don't want
such advises in the future (fully typed is such case) - then avoid
comments on putting me down.
Still living in a private world where JavaScript isn't an implementation
of ECMAScript, eh?
Still living in a private world where JavaScript == ECMAScript, Global
== window, only one Global per document, eh?
(just your wording back)
function MyObject() {
this.member = 'value';

return null;
}

var object = new MyObject();

to do? Return null? Raise an exception? Return an object but omit the
property? Shame it doesn't do any of those things: it returns the object
as if the return statement wasn't even there. Even if you only tested in
Fx or IE, you would have found that out for yourself.

Will you ever learn?
We are all learning - all our life. The danger is to decide one day
that you have nothing more to learn as you know everything you have to
know. That is really bad. The rest is always fixable.

Yes, it has to be a reference to an object used in the return
statement. Primitives are ignored. I was wrong with this one. That's a
drawback of my knowledge I guess: I don't give a damn of how something
is called or ticking until I need to know this to get my money. As I
never had to make a "constructor" constructing nothing, I did not look
that does return null do in the constructor call context. The singleton
I posted was used for years w/o any problems because you can return
other object reference instead of the newly created instance reference:

<script type="text/javascript">
var foo = new Object();

function AnObject(){
this.foo = 'bar';
return foo;
}

var obj = new AnObject();

alert(obj.foo); // undefined
</script>

- but of course you already knew it.

Oct 11 '06 #24
VK
I just hate these Books of ECMA liturgies,
>
And look where that gets you.
And where *that* gets you :-) (see a bit further)
The primary false statement under discussion here has been your
assertion that in a constructor the newly created object is added to
the scope chain.
I had a stupid (from my side) attempt to write something using your
regular ECMAScript lingo (scope chain, Activation etc.) and I did a
mistake. There are *current object* (pointed by [this]) and *default
object* (used say within with(){} construct). (If anyone doesn't like
these terms then she can go to hell - or to any descent
JavaScript/JScript reference).
So now I will not mix these terms and I know to avoid speaking
Ecmaspeak anymore. A valuable lesson.
There is no such thing as an "empty instance of MyObject", beyond there
being a native ECMAScritp obejct with its internal [[Prototype]]
property referring to the value of - myOjbect.prototype - at the time.
Again: what language are you talking about? JavaScript? Java? C++? C#?
VB? They all have "only one object type" in your terms. An Object
instance and say Applet instance in JVM are not marker by different
colors they are not "one is squared and other is rounded". They are
not, trust me. The same structure with different set of properties and
references to other objects.

import java.applet.*;
import java.awt.*;

public class test extends Applet {
String demo;

public void init() {
demo = (this instanceof Object) ? "true" : "false";
}

public void paint(Graphics g) {
g.drawString(demo, 20, 20);
// will be "true" of course, I did not test it,
// but feel free to make an applet to see it
}
}

So Java is a single object type language? Just fine... :-)

The Object object is contained in all other objects; all of its methods
and properties are available in all other objects. Every object "first
born" as a naked empty generic Object instance and it becomes something
different during the instantiation process. Yet every object remembers
its "babyhood": so besides of being an instanceof its class it also an
instanceof Object.

Trying to not be nasty (or pretending of trying not to :-) - it seems
to me that javascript is the only language you know - but you know it
very well. I noticed it before that you have a tendency to declare some
generic OOP things as javascript-specific. I have another problem
though: I know and I have to use too many programming languages, so
sometimes they clinch in my head.
The - null - value is not an object in javascript so a - return null; -
statement in a function that is called as a constructor will not result
in a null value. Try it:-

function AnObject(){
return null;
}
AnObject.prototype.testValue = 'XXX';

var obj = new AnObject();

alert(obj.testValue);

- which alerts 'XXX' rather than erroring, which is what it would do if
the - new AnObject() - expression returned null.
Silly me.
I was wrong with this one. That's a drawback of my knowledge I guess: I
don't give a damn of how something is called or ticking until I need to
know this to get my money. As I never had to make a "constructor"
constructing nothing, I did not look that does return null do in the
constructor call context. The singleton I posted was used for years w/o
any problems because you can return other object reference instead of
the newly created instance reference: but return [some primitive] is
silently ignored.

Oct 11 '06 #25
VK wrote:
>>I just hate these Books of ECMA liturgies,

And look where that gets you.

And where *that* gets you :-) (see a bit further)
I am quite happy with the position I am in now.
>The primary false statement under discussion here has
been your assertion that in a constructor the newly
created object is added to the scope chain.

I had a stupid (from my side) attempt to write something
using your regular ECMAScript lingo
You man the technical terminology from the language specification? That
is the terminology which is sufficiently well defined that anyone can
read the specification and know with absolute certainly what is meant,
and so understand anyone else using that terminology (correctly) to talk
about the language.
(scope chain, Activation etc.) and I did a
mistake.
Of course you did. To use technical terminology in a technical newsgroup
you have to understand what it means (or at least be interested in
learning what it means). Without understanding it using the terminology
just degrades it into nonsense jargon used as a smokescreen to disguise
ignorance and misconceptions. And that smokescreen is not going to be
very effective if attempted in a context where others actually do
understand the terminology. That is, you can impress people who don't
know any better but the people with the technical understanding can see
right through you.

However, your previous habit of making up your own 'technical' jargon is
really worse as it turns what you say into a sort of nonsense that cannot
even be corrected, as it has no real meaning for anyone else.
Unfortunately for the newcomers and novices who read this group 'nonsense
jargon' pretty much characterises your posts. Making it more difficult
for them to properly comprehend the concepts and terminology that really
does apply to javascript.
There are *current object* (pointed by [this]) and
*default object* (used say within with(){} construct).
Nonsense.
(If anyone doesn't like these terms then she can go to
hell -
That is a poor attitude, as anyone taking these terms seriously will
understand javascript worse than in they had heard them at all. You may
not be able to perceive it but you are doing harm when you talk this
nonsense on this newsgroup.
or to any descent JavaScript/JScript reference).
So now I will not mix these terms and I know to
avoid speaking Ecmaspeak anymore. A valuable lesson.
So you will only be using your made up (or inappropriately borrowed)
jargon form now on?
>There is no such thing as an "empty instance of MyObject",
beyond there being a native ECMAScritp obejct with its
internal [[Prototype]] property referring to the value of -
myOjbect.prototype - at the time.

Again: what language are you talking about?
Javascript. How many other languages would have instances of the native
ECMAScript object?
JavaScript? Java? C++? C#? VB? They all have "only one
object type" in your terms.
Strongly type languages have a very definite notion of objects being of
different types. And the compiled languages almost certainly carry those
distinctions into creating distinct structures in memory to represent
those objects.
An Object instance and say Applet instance in JVM are not
marker by different colors they are not "one is squared
and other is rounded". They are not,
You point is?
trust me.
I trust you not to know what you are talking about here either.
The same structure with different set of properties and
references to other objects.

import java.applet.*;
import java.awt.*;

public class test extends Applet {
String demo;

public void init() {
demo = (this instanceof Object) ? "true" : "false";
}

public void paint(Graphics g) {
g.drawString(demo, 20, 20);
// will be "true" of course, I did not test it,
// but feel free to make an applet to see it
}
}

So Java is a single object type language? Just fine... :-)
All Java objects are subclasses of the Java Object class (and as you
mentioned C++, that is not true in C++ ). The point of a subclass is that
it is a different type than its super-class. And the relationship is very
certain; you can cast a sub-class into its superclasses, but you cannot
cast a superclass instance into one of its subclasses.

In javascript, where there are no classes, and there is only one object
type no such restriction exists. What you call an "instance of MyObject"
is sufficiently flexible to be transferred into an instance of what is
conceptually a superclass of MyObject, and you can do that in javascript
precisely because all the objects are just instances of the native
ECMAScript object and so all of preciously the same type.
The Object object is contained in all other objects;
all of its methods and properties are available in
all other objects.
That is not true in javascript. Because the inheritance if through the
prototype chain it is entirely possible for a instance of the native
ECMAScript object to, for example, mask a method of the -
Object.prototype - object with a non-callable value. Effectively
rendering the method unavailable and unusable. You just cannot do that in
Java; Java objects can only overload the methods they inherit from the
Object base class with methods with the same signature.
Every object "first born" as a naked empty generic Object
instance and it becomes something different during the
instantiation process.
Where, and based upon what? C++ has no Object base class. Java objects
almost certainly come into existence as specific memory structures that
do no more, and no less, than accommodate objects of that one type
(because their type cannot be modified post instantiation and anything
else would waste resources).
Yet every object remembers its "babyhood": so besides of
being an instanceof its class it also an instanceof Object.
You do realise that the - instanceof - operator has very different
behaviour between Java and javascript? Attempting to draw comparisons
between the two languages based upon the results of uses of -
instanceof - is more likely to be misleading than anything else.
Trying to not be nasty
That's alright, the contempt I feel for you would negate the attempt if
made.
(or pretending of trying not to :-) - it seems
to me that javascript is the only language you know
Your perceptions are rarely accurate.
- but you know it very well.
If you really think I know javascript very well why do you argue when I
tell you that you are wrong, and if you are going to argue why don't you
test your case so you don't find yourself trying to defend an untenable
position?
I noticed it before that you have a tendency to declare
some generic OOP things as javascript-specific.
I have noticed in the past that what you say in connection with OOP
contains as many misconceptions as what you say when talking about
javascript.
I have another problem though: I know
Or, you think you 'know'. You behave as if you know something about
javascript, yet the evidence is that you know less than nothing about it.
and I have to use too many programming languages,
"Use" may be overstating what you do.
so sometimes they clinch in my head.
The contents of your head do seem very mixed-up.
>The - null - value is not an object in javascript so a
- return null; - statement in a function that is called
as a constructor will not result in a null value. Try it:-

function AnObject(){
return null;
}
AnObject.prototype.testValue = 'XXX';

var obj = new AnObject();

alert(obj.testValue);

- which alerts 'XXX' rather than erroring, which is
what it would do if the - new AnObject() - expression
returned null.

Silly me.
I was wrong with this one.
So you were wrong about the constructed object being added to the scope
chain, wrong about the constructed object being an "instance of MyObject"
and wrong about the behaviour of return statements in constructors. So
what exactly were you right about.

Look at how much time you have wasted by making the mistake of thinking
that you know what you are talking about when you have repeatedly been
told hat you do not.
That's a drawback of my knowledge I guess:
Mistaking what you have for "knowledge" is your main mistake.
I don't give a damn of how something is called or ticking
until I need to know this to get my money.
Yet you re willing to tell other people what is happening, and then
object to being corrected on the rare occasions when what you write is
sufficiently coherent to be corrected.
As I never had to make a "constructor" constructing nothing,
I did not look that does return null do in the constructor
call context.
Yet you frequently use - return null; - statements in functions that are
clearly intended to be used as constructors (and that error has been
pointed out to you in the past), and post examples of such code to this
group.

Think about that for a moment. You are writing code that you freely admit
you did not understand. You were putting such stamens into code
(presumably including code that you have been paid for) without knowing
what that code would actually do. That is not competent programming, it
is programming by coincidence and by mystical incantation.
The singleton I posted was used for years w/o any problems
because you can return other object reference instead of
the newly created instance reference: but return
[some primitive] is silently ignored.
Using 'it has worked for me for years' as your only justification for
writing particular lines of code is pretty much the definition of
"programming by coincidence".

You would not last five minutes in any of the software houses that I have
worked for (indeed you would not get through their doors in most cases).
It is amazing that you have got away with your incompetence for as long
as you claim you have (but then if you are as insane as you come across
you employment record may just be another of your fictions). I can
certainly understand your desire to remain anonymous. I would be deeply
ashamed of taking money of people for the code you write.

Richard.
Oct 11 '06 #26
Jeremy wrote:
Richard Cornford wrote:
>>
But still not reliable:-

var obj1 = new TestConstructor();

var obj2 = TestConstructor.call(obj1); // <- no - new -
// operator.

will alert "New Object" twice, when the second call is
not as a constructor. Also:-

var obj1 = new TestConstructor();

obj1.method = TestConstructor;

var obj2 = obj1.method();

- again will alert "New Object" twice when the second
call to - TestConstructor - is as a method not a
constructor.

The odds are good that the actual problem that the OP
is attempting to address does not really require a
reliable solution, but as we have seen there are
numerous possibilities, of more or less complexity and
with differing reliabilities and compatibilities.
Until the OP answers the question 'why?' knowing which
would best address the issue is not possible.

Interesting. Can't think of a way to fix those scenarios
without adding extraneous properties to the object, so
I guess you're right.
There is every possibility that they don't kneed fixing in the actual
context of application.
I also have never had to use function.call() in my entire
life, and I can't see any reason why you would want to attach
a constructor as a method to another object.

Then, I can't really see why it would ever be desirable to
call a constructor as a regular function. Seems like asking
for trouble, IMHO. I agree that the OP should explicate
his or her reasoning.
Absolutely. "Solutions" proposed in ignorance of the real problem that
they are intended to solve are unlikely to be truly successful, though
they may give that impression to anyone who needed to ask for help with a
solution in the first place.
If you have functionality that you want to use both in the
constructor and as a normal function, why not remove that
functionality and encapsulate it in a separate function
apart from the constructor?
Yes, I would consider that a very questionable design, but it is not
necessarily the issue in question here. There are, for example, people
trying to create 'library' code that is intend to be used by the most
unskilled developers, who want to second guess and error-correct for
those unskilled programmers. If that is the issue here then those
incompetent library end users may well do things as strange as using
the - call - method on a constructor, or making it into a method of an
object. In which case a very robust approach would be required.

Richard.
Oct 11 '06 #27
VK wrote:
<snip>
... . The statement alone that "returning null from a
constructor has no effect" demostrates such shiny lack
of a real javascript programming experience that I could
call [this] as "foobar property of foobarer" and I would
still remain in big plus by any "error-meter".
Do I take it from this little tirade that you think my suggestion that
your assertion that "If there is [return] statement in the constructor
and it is not "return this;", then return whatever pointed by this
statement" was false is so self-evidently not true my mere suggesting it
acts to completely destroy my credibility? That nothing you could
possible say, no matter how nonsensical, could be regarded as erroneous
in the light of it?

That would make it a pity I was correct in my assertion, as that rather
turns the credibility relationship on its head.

To be so absolutely confident in your beliefs that you will dismiss
correction out of hand while being so frequently demonstrated wrong is
less than rational.

Richard.
Oct 12 '06 #28
VK

Richard Cornford wrote:
VK wrote:
<snip>
... . The statement alone that "returning null from a
constructor has no effect" demostrates such shiny lack
of a real javascript programming experience that I could
call [this] as "foobar property of foobarer" and I would
still remain in big plus by any "error-meter".

Do I take it from this little tirade that you think my suggestion that
your assertion that "If there is [return] statement in the constructor
and it is not "return this;", then return whatever pointed by this
statement" was false is so self-evidently not true my mere suggesting it
acts to completely destroy my credibility? That nothing you could
possible say, no matter how nonsensical, could be regarded as erroneous
in the light of it?
Hey, I'm just getting to be a good student of you... Three years ago I
would never write something of this level of silly pathetic, however
bad my current mood would be. But having three years in a row nearly
every post with an error or an ambigousity followed by 4-5 well
balanced "VK is ignorant / VK is halfweet / don't listen VK" - that
makes a change I guess. At some point you think to get your abuser by
any mean - rather than thinking on the matter itself. There is
something left of my old one though: so deeply sorry for the false
statement I made and for an abusive comment to your side. Think that I
just had my finger cut off for that - please humbly accept it :-)

But: can you than explain why explicetly returning a reference to an
object from function-constructor does override default constructor
behavior: while returning a primitive is silently ignored? That is not
a "question with a trick" - I really would like to know, as well as to
know if this officially documented anywhere.

Oct 12 '06 #29
VK wrote:
Richard Cornford wrote:
>VK wrote:
<snip>
... . The statement alone that "returning null from a
constructor has no effect" demostrates such shiny lack
of a real javascript programming experience that I could
call [this] as "foobar property of foobarer" and I would
still remain in big plus by any "error-meter".

Do I take it from this little tirade that you think my
suggestion that your assertion that "If there is [return]
statement in the constructor and it is not "return this;",
then return whatever pointed by this statement" was false
is so self-evidently not true my mere suggesting it acts
to completely destroy my credibility? That nothing you
could possible say, no matter how nonsensical, could be
regarded as erroneous in the light of it?

Hey, I'm just getting to be a good student of you...
Three years ago I would never write something of this
level of silly pathetic, however bad my current mood
would be. But having three years in a row nearly every
post with an error or an ambigousity followed by 4-5 well
balanced "VK is ignorant / VK is halfweet / don't listen
VK" - that makes a change I guess.
Three years of posting nonsense and disregarding the corrections made is
what earned you the type of reactions you get now. While others listen
learn form corrections and do not repeat their mistakes your reaction to
being corrected is to assert that questioning your understanding is akin
to questioning a claim that the sky is blue (here by implication and
literally on number of occasions).
At some point you think to get your abuser by
any mean - rather than thinking on the matter itself.
You perceive technical corrections as abuse? You are offended by the
implication that you may not know what you are talking about, even though
that has been demonstrated on such a regular basis that no objective
observer could be left with the impression that you do?

Even my regular suggestions that what you post is best explained by
mental illness is not actually abuse (or even a criticism as such) but
instead an attempt to make you aware of a problem you apparently suffer
from and which you could take steps towards having treated if you
appreciated you problem. (Though a characteristic of not being rational
may be not being able to perceive irrational behaviour as irrational).

You have, from the beginning, been given assistance, in the form of
explanations and corrections. The tone of that assistance may have
changed over time, but that is a direct consequence of your continued
attitude that you are the only person here who actually understands
javascript and so you do not need to change to correct yourself. We are
now at a point where attempting to improve your understanding has been
sufficiently demonstrated futile and now the best approach to you is to
attempt to mitigate the considerable harm you attempt to do to others.
There is something left of my old one though: so deeply
sorry for the false statement I made and for an abusive
comment to your side.
But not sorry for wasting so much of everyone's time arguing that you
were right all along? No sorry for squandering the time of the people
correcting you for the umpteenth time so it could not be used assisting
the more deserving? Not sorry for insulting Matt for no better reason
than seeing for himself how wrong you were?
Think that I just had my finger cut off for that -
As has happened numerous times in the past and will happen again and
again in the future. You are the only person in a position to do
something about that. You can either do something about starting to learn
javascript, or you can be silent on the subject.
please humbly accept it :-)
If you were genuinely sorry you would do something about not repeating
your mistakes. You record suggests that having forced people to virtually
hammer the truth into you will teach you nothing beyond the single fact
(assuming your conceding the point actually represents you getting the
idea, which has not often been the case in the past) and you will make
the same mistake again, later today, tomorrow or the day after.
But: can you than explain why explicetly returning a
reference to an object from function-constructor does
override default constructor behavior: while returning
a primitive is silently ignored? That is not a "question
with a trick" - I really would like to know,
That is a question of motivation in language design, and so best asked of
the individuals responsible. For practical programming it is not
necessary to know why something is the case in the language being
programmed, only what is the case.
as well as to
know if this officially documented anywhere.
Why do you bother asking when you already know where the answer can be
expected to be found; ECMA 262, 3rd Ed. Section 13.2.2, clauses 7 and 8
of the specified algorithm for a function object's [[Construct]] method.

But of course you don't believe that ECMA 262 can be used to understand
the behaviour that can be expected from an ECMAScript implementation.

Richard.
Oct 12 '06 #30
VK

Richard Cornford wrote:
Three years of posting nonsense...
<snip>

I'm taking it as my apology for this particular case is accepted,
moving forward.
You perceive technical corrections as abuse?
A single-line post like "Do not listen VK" or "You have no idea about
JavaScript" can be hardly taken as "technical corrections". They are
especially hard to take then I know for sure that people issuing such
statements have very weak idea of many important JavaScript/JScript/DOM
programming aspects: yet positionning themselves as knowing everything
one has to know for client-side development. That's funny most of the
time, but sometimes the sh** hits the fan.

<return statement in function-constructor>
you don't believe that ECMA 262 can be used to understand
the behaviour that can be expected from an ECMAScript implementation.
It can, but very rarely: in application to myself that was twice in
four years, including the current case:
1) var statements
2) return null in constructor

13.2.2 [[Construct]]
When the [[Construct]] property for a Function object F is called, the
following steps are taken:

1. Create a new native ECMAScript object.

// Why not start then from "allocate memory for..."
// or even "processor executes assembly code..."
// For programming on a given language it is irrelevant
// For making an engine for a given language it is way not
// enough.

2. Set the [[Class]] property of Result(1) to "Object".

// On a human language it means that on step 1-2
// we are creating new Object() and not say new Function().

3. Get the value of the prototype property of the F.
4. If Result(3) is an object, set the [[Prototype]] property
of Result(1) to Result(3).
5. If Result(3) is not an object, set the [[Prototype]] property
of Result(1) to the original Object prototype object as
described in section 15.2.3.1.
function AnObject() {
alert(typeof AnObject.prototype); "object" of course
alert(this.prototype == AnObject.prototype); // false
alert(this.prototype == Object.prototype); // false
alert(this.prototype == Function.prototype); // false
}
var obj = new AnObject;

I'm out of ideas: what does step 4 mean? Is it a fancy way to say that
..constructor property of the newly created instance points to the
function-constructor (AnObject)? Something else?

6. Invoke the [[Call]] property of F, providing Result(1)
as the this value and providing the argument list passed
into [[Construct]] as the argument values.

// Create an empty instance of given "class", set this instance
// as current object ([this] value) for constructor,
// call the constructor with provided arguments.

7. If Type(Result(6)) is Object then return Result(6).
// else
8. Return Result(1).

// That is really valuable part, this is where my mistake was.
// So in order to override the default constructor behavior
// you always have to return something with typeof "object".

So in case like:
var obj = new AnObject();

ECMAScript to English translation:

1. Create an empty instance of AnObject object.

2. Set this instance as current object ([this] value).for AnObject
constructor.

3. Call AnObject constructor.

4. Optionally add fields and methods to the new instance:
or just leave it empty.

5. If there is not return statement then
return the result of step 4 (equivalent of "return this");
Else if there is return statement
and the return value is typeof "object" then
return a reference to that object.
If it is not "return this" and if you did not store
a reference to [this] somewhere on the step 4 then
the newly created instance will remain dereferenced and
eventually removed by the Garbage Collector.
Else
disregard return statement and return the result of
step 4 (equivalent of "return this");

The first if-clause, however obvious it may be, is important to mention
for Perl programmers - as well as for programmers of other languages
where function/sub returns either return value or (if no return
statement) the *result of execution of the last statement* in the
function body. That is why you see sometimes:
function AnObject() {
...
return this;
}
That seems making you nervous every time :-) but it is not to upset
c.l.j. gurus: just another sample of a "languages' clinching".

Oct 12 '06 #31
VK wrote:
Richard Cornford wrote:
Three years of posting nonsense...
<snip>

I'm taking it as my apology for this particular case is accepted,
moving forward.
You perceive technical corrections as abuse?

A single-line post like "Do not listen VK" or "You have no idea about
JavaScript" can be hardly taken as "technical corrections".
They are not, they are just advice to the wider world, and they do not
appear as responses to your postes.
They are especially hard to take then I know for sure
But that is precisely your problem. What you know, what you "know for
sure" is rubbish. That is what got you apologising for posting evident
nonsense here. If you had not been so sure that you know what you were
talking about you might have bothered testing what return null actually
did in a constructor instead of declaring the suggestion that it would
not result in null being returned so obviously wrong as to destroy the
credibility of anyone who maintained such.
that people issuing such statements have very weak idea of many
important JavaScript/JScript/DOM
But they don't. You are the one with the very week idea of many
important aspects of javascript. What you think of the understanding of
others is o no real relevance as you just don't have nay applicable
knowledge with which to judge the knowledge of others.
programming aspects: yet positionning themselves as knowing
everything one has to know for client-side development.
The only thing being implied by the assertion that most of what you
post is nonsense, incomprehensible, false and/or the worst approach
available to any given issue is that someone has recognised you for
what you are.
That's funny most of the
time, but sometimes the sh** hits the fan.

<return statement in function-constructor>
you don't believe that ECMA 262 can be used to understand
the behaviour that can be expected from an ECMAScript implementation.

It can, but very rarely: in application to myself that was twice in
four years, including the current case:
1) var statements
2) return null in constructor

13.2.2 [[Construct]]
When the [[Construct]] property for a Function object F is called, the
following steps are taken:

1. Create a new native ECMAScript object.

// Why not start then from "allocate memory for..."
Because allocating memory would be implementation specific and the
standard for javascript only defines behaviour (and how would you
allocate memory in an implementation written in Java or javascript?).
// or even "processor executes assembly code..."
Ditto.
// For programming on a given language it is irrelevant
// For making an engine for a given language it is way not
// enough.
You are the only person who has made the mistake of thinking that the
language specification is a javascript engine specification. You will
find that any one of your misconceptions will tend to act to get in the
way of your understanding new information and so generate new
misconceptions.
2. Set the [[Class]] property of Result(1) to "Object".

// On a human language it means that on step 1-2
// we are creating new Object() and not say new Function().

3. Get the value of the prototype property of the F.
4. If Result(3) is an object, set the [[Prototype]] property
of Result(1) to Result(3).
5. If Result(3) is not an object, set the [[Prototype]] property
of Result(1) to the original Object prototype object as
described in section 15.2.3.1.
function AnObject() {
alert(typeof AnObject.prototype); "object" of course
alert(this.prototype == AnObject.prototype); // false
Object objects do not have - prototype - properties. Those properties
are only natively provided on Function objects. Thus - this.protoype -
can be expected to be undefined, and so not equal to anything but
another undefined or null. As I have repeatedly said; you failure to
appreciate the nature, and role of, prototypes in javascript is
evident, and has lead to much nonsense issuing form you.
alert(this.prototype == Object.prototype); // false
The - this.prototype - property accessor will resole as undefined here
as well.
alert(this.prototype == Function.prototype); // false
And here.
}
var obj = new AnObject;

I'm out of ideas: what does step 4 mean?
It means what it says; that the internal [[Prototype]] property of the
object is set the value of the - prototype - property of the
constructor function (except when that value is not an object).
Is it a fancy way to say that
.constructor property of the newly created instance points to the
function-constructor (AnObject)? Something else?
It mans what it says. It really is not that complicated, though your
inability to differentiate between the property that refers to the root
of the prototype chain and the - prototype - property of constructors
will tend to render it incomprehensible for you.
6. Invoke the [[Call]] property of F, providing Result(1)
as the this value and providing the argument list passed
into [[Construct]] as the argument values.

// Create an empty instance of given "class",
The instance was created in step 1, and it is an instance of the native
ECMAScript object.
set this instance
// as current object ([this] value) for constructor,
// call the constructor with provided arguments.

7. If Type(Result(6)) is Object then return Result(6).
// else
8. Return Result(1).

// That is really valuable part, this is where my mistake was.
// So in order to override the default constructor behavior
// you always have to return something with typeof "object".
The result is that - new - operations only ever return objects (or
throw exceptions).
So in case like:
var obj = new AnObject();

ECMAScript to English translation:

1. Create an empty instance of AnObject object.
Creates an instance of the native ECMAScript object.
2. Set this instance as current object ([this] value).for AnObject
constructor.
Are you omitting the assignment to the [[Prototype]] because it went
over your head?
3. Call AnObject constructor.
Would be better worded as "executes the function body", as that is
effectively what the internal [[Call]] method does.
4. Optionally add fields and methods to the new instance:
or just leave it empty.

5. If there is not return statement then
return the result of step 4 (equivalent of "return this");
Else if there is return statement
and the return value is typeof "object" then
return a reference to that object.
If it is not "return this" and if you did not store
a reference to [this] somewhere on the step 4 then
the newly created instance will remain dereferenced and
eventually removed by the Garbage Collector.
Else
disregard return statement and return the result of
step 4 (equivalent of "return this");

The first if-clause, however obvious it may be, is important to mention
for Perl programmers - as well as for programmers of other languages
where function/sub returns either return value or (if no return
statement) the *result of execution of the last statement* in the
function body. That is why you see sometimes:
function AnObject() {
...
return this;
}
That seems making you nervous every time :-) but it is not to upset
c.l.j. gurus: just another sample of a "languages' clinching".
You have degenerated to gibberish again.

Richard.

Oct 12 '06 #32
VK
<snip>
Business first, the netiquette, apologies and the VK's issue in the
global politics just one step later: if you dont mind.
1. Create a new native ECMAScript object.
// Why not start then from "allocate memory for..."
Because allocating memory would be implementation specific and the
standard for javascript only defines behaviour (and how would you
allocate memory in an implementation written in Java or javascript?).
Java and JavaScript do not provide direct memory *access* by using
language tools (unless a vulnerability exploit by specially constructed
code). But their objects are allocated in the same memory: as any other
objects in any other language. Positions 1 and 2 describe a generic
scavenger (~= heap) construction: very incompletely and in no relevance
to actual mechanics of say Microsoft JScript engine. But these
description defaults are really irrelevant to the *language* standard
compliance, as say it is irrelevant the bytes reading order on my
machine - as long as new Object(); doesn't crash your UA.
So I keep wondering that this part is doing here.
// For programming on a given language it is irrelevant
// For making an engine for a given language it is way not
// enough.
Ditto
<after your explanations snip step 4, 5, 6 as irrelevant to the
*language*, still roaming below it>
As I have repeatedly said; you failure to
appreciate the nature, and role of, prototypes in javascript is
evident
The role of .prototype or the role of [[Prototype]] ?
I do appreciate a lot the prototype property in JavaScript (though I'm
using it only for default objects augmentation, so rather occasionally
I'm afraid).
At the same time I couldn't care less about [[Prototype]] or [[Class]]
- unless one day I will be hacking a script engine and by some mystery
it will appear to be the ECMAScript engine.

So steps 1, 2, 3, 4, 5 for the *language* user are only one step:

1. Create an empty object and define F as its constructor.
6. Invoke the [[Call]] property of F, providing Result(1)
as the this value and providing the argument list passed
into [[Construct]] as the argument values.
Very curly said but now has some sense. To bring even more sense into
it:

6. (really 2. now) Set the Result(1) as current object for F
constructor and call the constructor with the provided arguments (if
any).
btw: if you don't have any arguments to pass, you can omit parenthesis
in the constructor call:
var obj = new MyObject();
or
var obj = new MyObject;
are equivalent. I don't know where ECMA says about, but sure they do.
Just came in my mind while typing.
The instance was created in step 1, and it is an instance of the native
ECMAScript object.
An object, which is not an Object or Function or anything else, is not
an object in the programming sense. That is still below the language
level so it doesn't bother us; but I mentioned it already.

4. Optionally add fields and methods to the new instance:
or just leave it empty.

5. If there is not return statement then
return the result of step 4 (equivalent of "return this");
Else if there is return statement
and the return value is typeof "object" then
return a reference to that object.
If it is not "return this" and if you did not store
a reference to [this] somewhere on the step 4 then
the newly created instance will remain dereferenced and
eventually removed by the Garbage Collector.
Else
disregard return statement and return the result of
step 4 (equivalent of "return this");
You have degenerated to gibberish again.
*Now* what's wrong? That is the formal algorithm from the language
point of view (or did you mean "gibberish" about some people using -
return this - in their constructors and you pointing out to that?)

Here is the code to illustrate the formal algorithm or -return-
statement treatment in javascript constructor:

<html>
<head>
<title>Demo</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var myVar = true;

function MyObjectOne() {
}

function MyObjectTwo() {
return new String('foobar');
}

function MyObjectThree() {
return 'foobar';
}

function init() {
var objOne = new MyObjectOne;
var objTwo = new MyObjectTwo;
var objThree = new MyObjectThree;

// Default behavior:
alert(objOne instanceof MyObjectOne); // true

// Overloaded constructor:
alert(objTwo instanceof MyObjectTwo); // false

// return value is not an object: fall back to
// the default behavior:
alert(objThree instanceof MyObjectThree); // true

alert(objOne); // "[object Object]"

alert(objTwo); // "foobar"

alert(objThree); // "[object Object]"
}

window.onload = init;
</script>
</head>

<body>

</body>
</html>

Oct 12 '06 #33
In article <11*********************@m73g2000cwd.googlegroups. com>, VK
<sc**********@yahoo.comwrites

<snip>
>Again: what language are you talking about? JavaScript? Java? C++? C#?
VB? They all have "only one object type" in your terms. An Object
instance and say Applet instance in JVM are not marker by different
colors they are not "one is squared and other is rounded". They are
not, trust me. The same structure with different set of properties and
references to other objects.
<snip>

In Java an object consists of a fixed number of bytes, possibly
containing pointers to objects consisting of a fixed number of bytes,
possibly containing pointers ... .

The fixed number of bytes is decided by the compiler when it reads the
class definition. If two objects have a different fixed number of bytes
then they can't possibly belong to the same Java class. So yes, one is
'squared' and the other is 'rounded'.

We can't trust you here because you are wrong.

>The Object object is contained in all other objects; all of its methods
and properties are available in all other objects.
'The' Object object is *not* contained in all other objects. What all
objects have is a prototype chain that is guaranteed, in ECMAScript v3,
to end with the same very special object. This special object has
several properties that are functions. Some of these functions implement
operations such as hasOwnProperty that cannot be coded by us.

The reason all objects have something in common is because they all
share this special prototype object. (In ECMAScript v3).

>Every object "first
born" as a naked empty generic Object instance and it becomes something
different during the instantiation process. Yet every object remembers
its "babyhood": so besides of being an instanceof its class it also an
instanceof Object.
<snip>

A new-born, naked, object is not an Object instance because it has not
been processed by the constructor function named Object. If it is
processed by MyObject, Date, Array, or anything else except Object, it
never will be an Object instance.

A new-born object has nothing to remember. It is given things to
'remember' during the construction process : its prototype chain, its
programmer-defined properties, etc.
John
--
John Harris
Oct 12 '06 #34
VK wrote:
<snip>
Business first, the netiquette, apologies and the VK's issue in the
global politics just one step later: if you dont mind.
1. Create a new native ECMAScript object.
// Why not start then from "allocate memory for..."
>Because allocating memory would be implementation specific and the
standard for javascript only defines behaviour (and how would you
allocate memory in an implementation written in Java or javascript?).

Java and JavaScript do not provide direct memory *access* ...
<snip>

So there would be no sense in a document that specifies how javascript as
a language is supposed to behave mentioning something that could not be
implemented in languages that could be used to implement javascript. It
was irrational of you to propose the inclusion of that impractical
irrelevance in the specification.
... . But these description defaults are really irrelevant
to the *language* standard compliance, ...
Precisely.
So I keep wondering that this part is doing here.
Your mentioning memory allocation was a pointless inclusion on your part,
and if you are wondering why you mentioned it its looks you will never
satisfactorily explain it to anyone else.
>> // For programming on a given language it is irrelevant
// For making an engine for a given language it is way not
// enough.

Ditto

<after your explanations snip step 4, 5, 6 as irrelevant
to the *language*, still roaming below it>
You are a fool if you cannot see that the language needs to be precise
about what is going to happen if someone assigns a non-object property to
the constructor's - prototype - property. However, as you have once again
demonstrated that you don't comprehend the role of prototypes in the
language, and given your record an leaving huge logical holes in the
algorithms you implement, I should not be surpassed at yet another
demonstration of your folly.
>As I have repeatedly said; you failure to
appreciate the nature, and role of, prototypes
in javascript is evident

The role of .prototype or the role of [[Prototype]] ?
The role of prototypes is manifest in the relationship between the two.
I do appreciate a lot the prototype property in JavaScript
Bullshit. What you have written above directly contradicts that. In this
very thread you posted:-

| alert(this.prototype == AnObject.prototype); // false

- as some sort of attempt to demonstrate something (and that was nowhere
near the first time you have done so). The inevitability of the -
false - result is lost on you.
(though I'm using it only for default objects augmentation,
so rather occasionally I'm afraid).
And you have the nerve to comment of the relative simplicity of other
approaches, when you are letting your ignorance of a fundamental aspect
of javascript keep you from seeing where the real simplicity is to be
found in object creation.
At the same time I couldn't care less about [[Prototype]]
or [[Class]]
They are both there for very good reasons. Indeed everything in the
specification is there for a very good reason, but if you prefer to
ignore them you will find yourself back here again being shown up for
posting your fictions in the guise of facts.
- unless one day I will be hacking a script engine and by
some mystery it will appear to be the ECMAScript engine.
LOL.
So steps 1, 2, 3, 4, 5 for the *language* user are only
one step:
It is not the style of ECMA 262 to combine too many operations into a
single step in its algorithms. That is probably a good thing as it avoids
them becoming ambiguous or accidentally skipping possibilities.
1. Create an empty object and define F as its constructor.
There is no assignment to a - constructor - property in the construction
of an object in javascript. (The - constructor - property is accounted
for in Section 13.2, during the creation of function objects). It is the
assignment to the [[Prototype]] property (that you have just dismissed as
irrelevant) that explains how the new object comes to inherit a -
constructor - property.

Also, labelling a new instance of the native ECMAScript object "empty" is
likely to be confusing as the assignment to the [[Prototype]] property
brings with it a number of other properties, and so the object will not
behave as if it was empty.
>>6. Invoke the [[Call]] property of F, providing Result(1)
as the this value and providing the argument list passed
into [[Construct]] as the argument values.

Very curly said but now has some sense.
It is astounding to see the extent to which information plus the
application of your mental processes results in your understanding less.
To bring even more sense into it:
Fat chance.
6. (really 2. now) Set the Result(1) as current object
There is no point in introducing your bogus "current object" jargon here.
The existing "providing Result(1) as the *this* value" is sufficient, and
does not introduce the questions of how the global object gets to be "the
current object" in execution contexts which do not result from the
execution of a function as a method or a constructor, and it doesn't
raise the question of what sense "current object" could have in
functional and/or procedural javascript code.
for F constructor and call the constructor with the
provided arguments (if any).
btw: if you don't have any arguments to pass, you can
omit parenthesis in the constructor call:
var obj = new MyObject();
or
var obj = new MyObject;
are equivalent. I don't know where ECMA says about,
but sure they do.
ECMA 262, 3rd ed. Section 11.2.2;the production rules and algorithms for
the - new - operator, of course.
Just came in my mind while typing.
That doesn't surprise me, given how directionless your mind is.
>The instance was created in step 1, and it is an instance
of the native ECMAScript object.

An object, which is not an Object or Function or anything
else, is not an object in the programming sense.
What are you talking about now? The native ECMAScript object is an
object. In fact it is the only type of object in javascript, and function
objects are also instances of the native ECMAScript object (inevitably as
it is the only object type in javascript).
That is still below the language level so it doesn't
bother us; but I mentioned it already.
It read more like irrelevant ravings.
>>4. Optionally add fields and methods to the new
instance:
or just leave it empty.

5. If there is not return statement then
return the result of step 4 (equivalent of "return this");
Else if there is return statement
and the return value is typeof "object" then
return a reference to that object.
If it is not "return this" and if you did not store
a reference to [this] somewhere on the step 4 then
the newly created instance will remain dereferenced and
eventually removed by the Garbage Collector.
Else
disregard return statement and return the result of
step 4 (equivalent of "return this");
You have edited out a big chunk of what I quoted here without marking the
edit. That is disingenuous to say the least. However, I suppose
disingenuous quoting may be as easily attributed to insanity (that is,
you don't know any better because you cannot follow simple sequences of
statements) as it could to dishonesty.
>You have degenerated to gibberish again.

*Now* what's wrong?
The material I was commenting upon (that you edited out from above this
quite) degenerated into meaningless gibberish. That is, it was an
aggregation of words in a form that did not always qualify as sentences
and/or from which meaning could not be derived.
That is the formal algorithm from the language
point of view
The quote of yours I was commenting upon (that you have edited to give a
dishonest impression of what I was commenting upon) was not a formal
algorithm of anything. And the quote you retained does not really qualify
as one either, though given the compute code you write I can see how you
might mistake it for one.
(or did you mean "gibberish" about some people using -
return this - in their constructors and you pointing
out to that?)
No, I was commenting upon the text that I quoted directly above the
comment that I made (the text you edited out).
Here is the code to illustrate the formal algorithm
<snip>

And here is the code that demonstrates that the [[Construct]] method
never assigns a value the - constructor property of an object it
creates:-

function AnObject(){
;
}

var obj = new AnObject();

AnObject.prototype.constructor = null;

alert(obj.constructor);

- And unlike you I am capable of explaining how that demonstrates that
no - constructor - property is assigned to the object during its
construction:

If a property is assigned to an object and the object does not have that
property itself (even if one of its prototypes does have the property) a
new property of the object is created. Thus if a - constructor - property
was assigned a value during the creation of an object that property would
mask any property on the object's prototype chain. Once the object was
created no assignment to a prototype of the object could influence the
value returned by reading that property of the object. But here assigning
a value to the - constructor - property of the object referred to by
the - prototype - property of the constructor results in reading the -
constructor - property of the _previously_ created object instance
reflecting the value just assigned.

The ECMA 262 algorithm fully explains what happens during the
construction of the object. While your efforts are still making
statements that are demonstrably false, even though you have read (even
cited) the algorithm.

Richard.
Oct 12 '06 #35
VK wrote:
Richard Cornford wrote:
[snip]
>You perceive technical corrections as abuse?

A single-line post like "Do not listen VK" or "You have no idea about
JavaScript" can be hardly taken as "technical corrections".
Who has made a single line reply like that? Any regular in this group
would quote you, at the very least!
They are especially hard to take then I know for sure that people
issuing such statements have very weak idea of many important
JavaScript/JScript/DOM programming aspects:
Though in the past I haven't agreed with Richard's diagnoses of insanity
(I've preferred stubbornness or stupidity), I think that might just
change my mind.
yet positionning themselves as knowing everything one has to know for
client-side development.
Who's done that? You're the most intransigent person I've ever
encountered, despite being corrected an innumerable number of times.

[snip]
<return statement in function-constructor>
>you don't believe that ECMA 262 can be used to understand the
behaviour that can be expected from an ECMAScript implementation.

It can, but very rarely: in application to myself that was twice in
four years,
You either have a very poor memory, or you are deluded.

[snip]
13.2.2 [[Construct]]
When the [[Construct]] property for a Function object F is called, the
following steps are taken:

1. Create a new native ECMAScript object.

// Why not start then from "allocate memory for..."
That would be too specific. The ECMAScript specification defines
behaviour. Implementations may implement the language however they wish
so long as one can expect the described behaviour.
// or even "processor executes assembly code..."
Now you're just being facetious.
// For programming on a given language it is irrelevant
No, it isn't.
// For making an engine for a given language it is way not
// enough.
No, it isn't.

For want of a better expression, that algorithm step describes the
creation of a "bare" object: there are no internal properties set (such
as [[Value]] and [[Prototype]]), some of the internal methods like
[[Get]] and [[Put]] are, but not special methods such as
[[HasInstance]], [[Call]], and the unique [[Get]] method of array instances.
2. Set the [[Class]] property of Result(1) to "Object".

// On a human language it means that on step 1-2
// we are creating new Object() and not say new Function().
Not at all. Creating an Object object involves setting the prototype
chain and calling the constructor function, neither of which is
performed in this step nor the preceding one.

Note that the constructor functions of built-in and host objects may
(and do) replace the value of the [[Class]] property, so don't be
confused by the value 'Object'.
3. Get the value of the prototype property of the F.
4. If Result(3) is an object, set the [[Prototype]] property
of Result(1) to Result(3).
5. If Result(3) is not an object, set the [[Prototype]] property
of Result(1) to the original Object prototype object as
described in section 15.2.3.1.
[snip]
I'm out of ideas: what does step 4 mean?
The internal [[Prototype]] property represents the prototype chain. It
is through this property that the [[Get]] method will search when
looking for a property in a member accessor (if that property is not
present on the object itself).

For example,

function myFunction() {}

myFunction.valueOf()

The identifier, myFunction, will be resolved against the scope chain to
obtain a reference to a function object. The [[Get]] method will then be
called on that object with argument 'valueOf'. Function object instances
do not have valueOf properties, so the [[Get]] method will check if
there is a non-null [[Prototype]] property and, if there is, call its
[[Get]] method with the same argument. The [[Prototype]] property of a
function instance is the Function prototype object. This object will not
have a valueOf property either, so again a check will be made for
another [[Prototype]] property. The [[Prototype]] property of the
Function prototype object is the Object prototype object. This object
does have a valueOf property, and (eventually) the [[Call]] method of
this property value will be called.

[snip]
6. Invoke the [[Call]] property of F, providing Result(1)
as the this value and providing the argument list passed
into [[Construct]] as the argument values.

// Create an empty instance of given "class",
No, just an empty ECMAScript native object.
// set this instance as current object ([this] value) for constructor,
// call the constructor with provided arguments.
The term "current object" aside (which still has no intrinsic meaning),
that's about right, though if that was an overall summary, you missed
some important steps.
7. If Type(Result(6)) is Object then return Result(6).
// else
That's implied, is it not? Would it really be necessary to write:

if (condition) {
return ...;
} else {
return ...;
}

instead of

if (condition) {
return ...;
}
return ...;

? I think not.
8. Return Result(1).

// That is really valuable part, this is where my mistake was.
// So in order to override the default constructor behavior
// you always have to return something with typeof "object".
No, one must return /an/ object: typeof null is also 'object'.
So in case like:
var obj = new AnObject();

ECMAScript to English translation:

1. Create an empty instance of AnObject object.
I don't think one could really say that the object could be considered
an AnObject object until the constructor function has been run (and
completed successfully). At this point, the object is just a native
ECMAScript object with the [[Class]] and [[Prototype]] properties set
(assuming that's your implication), and that means it can hardly be
called empty.
2. Set this instance as current object ([this] value).for AnObject
constructor.
That phrase again...
3. Call AnObject constructor.

4. Optionally add fields and methods to the new instance:
or just leave it empty.
Sorry? Once the constructor has been called, there are only two
operations left: determine the returned type, and depending on that
result, either return the object created in step 1 or the object
returned from the constructor function.
5. If there is not return statement then
return the result of step 4 (equivalent of "return this");
Else if there is return statement
and the return value is typeof "object" then
return a reference to that object.
That's complicating things unnecessarily: if there is no return
statement, the constructor function will return undefined just like any
other function. As such a value isn't an object, it would be treated in
the same way as other primitives.

[snip]
The first if-clause, however obvious it may be, is important to mention
for Perl programmers
I don't see why. Any sensible programmer from any language background
should learn this language rather than assume they know how it works
(because they probably don't, just like anyone else first time around).

[snip]

Mike
Oct 12 '06 #36
Michael Winter wrote:
VK wrote:
<snip>
>They are especially hard to take then I know for sure that
people issuing such statements have very weak idea of many
important JavaScript/JScript/DOM programming aspects:

Though in the past I haven't agreed with Richard's diagnoses
of insanity (I've preferred stubbornness or stupidity), I
think that might just change my mind.
<snip>

I considered stubbornness and stupidity for a long time, and I also
considered that VK's problem was a very limited comprehension of English
(probably resulting from it being a second+ language) but in the end none
of them (or even all of them) were capable of fully explaining his posts
(particularly the very illogical 'reassign' he demonstrates, or the truly
incomprehensible 'streams of consciousness' he sometimes posts).

I am not particularly keen to talk about it but I knew someone for whom
manic depression manifested itself in here early twenties. A cyclic
illness where long periods of lucidity are interrupter by interrupted by
what are (quite appropriately) called manic episodes. She was a very
intelligent woman (the only woman I have ever known who could reliably
beat me at chess) and quite interesting and entertaining to talk to. But
as she went into the manic episodes you would be talking to her, and
everything would be going along the lines of a normal conversation, when
suddenly she would come out with a piece of reasoning so disjointed that
is was difficult to attribute it to the same person.

After experiencing a couple of cycles these first steps on the descents
into madness became very recognisable, I would think "here we go again",
and within a week she would have descend so far as to have been committed
to hospital for a couple of months to 'recover'.

There is something about the style of 'reasoning' I experienced than that
has become recognisable in VK's posts. They are just too far from the
products of the thought processes of a rational mind for hits of mental
illness to be dismissed.

Richard.
Oct 12 '06 #37
VK
Richard Cornford wrote:
There is no point in introducing your bogus "current object" jargon here.
I mostly lost the interest to this discussion: I learned an important
thing (at least important for me) about return values in constructors,
and there is nothing more to learn or discuss on the subject. Your
phantasmagorias about some "native ECMAScript object" and its extremely
important for the language yet invisible in the language [[properties]]
are giving me too much of a heartburn, sorry.

Outside of the main topic about function-constructors you'd like to
point that you are the one with a proprietary jargon used in ECMAScript
specs and unknown in any regular language references.

Netscape Client-Side JavaScript Reference (archive copy):

<http://docs.sun.com/source/816-6408-10/ops.htm#1043482>
The this keyword refers to the current object.
In general, in a method this refers to the calling object.

<http://docs.sun.com/source/816-6408-10/stmt.htm#1004910>
with
Establishes the default object for a set of statements.
Core JavaScript 1.5 Reference
<http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Special_Op erators:this_Operator>
The this keyword refers to the context object (a.k.a. current object).
In general, in a method, this refers to the calling object.

<http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Statements:with>
Extends the scope chain for a statement.
(Seems as edited in rush as "extends the scope chain" has no practical
sense, I would bring it back to the Netscape's original form if you
don't mind).
Microsoft JScript reference:
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/8510a00b-2f14-4700-a276-4d9a523c5112.asp>

this Statement
Refers to the current object.

<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/892c7621-ae9e-4c10-8adb-05532274b1ca.asp>
with Statement
Establishes the default object for a statement.

Do I have to keep going with more quotes?

Oct 14 '06 #38

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

Similar topics

6
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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 projectplanning, coding, testing,...

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.