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

Discussion in 'Javascript' started by jht5945@gmail.com, Oct 10, 2006.

  1. Guest

    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 10, 2006
    #1
    1. Advertising

  2. marss Guest

    напиÑав:
    > 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. :)
    marss, Oct 10, 2006
    #2
    1. Advertising

  3. VK Guest

    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.
    VK, Oct 10, 2006
    #3
  4. 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.
    Richard Cornford, Oct 10, 2006
    #4
  5. VK Guest

    > > 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>
    VK, Oct 10, 2006
    #5
  6. 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.
    Richard Cornford, Oct 10, 2006
    #6
  7. VK Guest

    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.
    VK, Oct 10, 2006
    #7
  8. Matt Kruse Guest

    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
    Matt Kruse, Oct 10, 2006
    #8
  9. VK Guest

    > 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?
    VK, Oct 10, 2006
    #9
  10. Guest

    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, 2006
    #10
  11. Andy Dingley Guest

    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.
    Andy Dingley, Oct 10, 2006
    #11
  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.
    Richard Cornford, Oct 10, 2006
    #12
  13. 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.
    Richard Cornford, Oct 10, 2006
    #13
  14. wrote:
    > 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.
    Richard Cornford, Oct 10, 2006
    #14
  15. VK Guest

    > 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.
    VK, Oct 11, 2006
    #15
  16. Matt Kruse Guest

    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
    Matt Kruse, Oct 11, 2006
    #16
  17. VK Guest

    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".
    VK, Oct 11, 2006
    #17
  18. 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.
    Richard Cornford, Oct 11, 2006
    #18
  19. Jeremy Guest

    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
    Jeremy, Oct 11, 2006
    #19
  20. runsun pan Guest

    Jeremy wrote:

    > How about this:
    >
    > function TestConstructor()
    > {
    > if(this.constructor == TestConstructor)
    > alert("New Object");
    > else
    > alert("Function Call");
    > }
    >
    > Jeremy


    good and simple.
    runsun pan, Oct 11, 2006
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. CRON
    Replies:
    24
    Views:
    200,484
    Adrienne Boswell
    Jun 20, 2006
  2. Johnny
    Replies:
    3
    Views:
    445
    Robert Kern
    Aug 23, 2005
  3. Hari Sekhon
    Replies:
    0
    Views:
    496
    Hari Sekhon
    Jun 20, 2006
  4. Vinko Vrsalovic

    int func() v/s int func(void)

    Vinko Vrsalovic, Jan 21, 2005, in forum: C Programming
    Replies:
    14
    Views:
    1,287
    Villy Kruse
    Jan 24, 2005
  5. Alex Vinokur
    Replies:
    6
    Views:
    344
    Tor Rustad
    Nov 18, 2006
Loading...

Share This Page