Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #14580

Re: Function Objects

From Stefan Weiss <krewecherl@gmail.com>
Newsgroups comp.lang.javascript
Subject Re: Function Objects
Date 2012-06-20 02:09 +0200
Organization albasani.net
Message-ID <jrr4cc$k5u$1@news.albasani.net> (permalink)
References <bm22u7l5dbs0rrdeloru3fd3sct7n8g201@4ax.com>

Show all headers | View raw


On 2012-06-20 01:35, Gene Wirchenko wrote:
>     I can code
> 
> var Output;
> Output=document.write;
> Output("This is the output.");
> 
> but I do not get the output.  I get an error of "Error: Invalid
> calling object".

In your example, Output is assigned a reference to the document object's
write method - just the method, not the object. The fact that write
originally "belonged" to document is now lost.

You can still get the same result if you restore that connection:

  Output.call(document, "This is the output.");

(Tested in Firefox and Chrome, but not in IE. document is a host object,
so the usual warnings apply.)

The effect may be easier to understand if you use a simpler
self-contained example without host objects:

    var dog = {
        noise: "wow!",
        bark: function () { alert(this.noise); }
    };

    dog.bark();  // "wow!"

    var alias = dog.bark;

    alias();  // "undefined"

The last line yields "undefined" because |this| in the function body now
refers to the global object, which has no "noise" property.

- stefan

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Function Objects Gene Wirchenko <genew@ocis.net> - 2012-06-19 16:35 -0700
  Re: Function Objects Stefan Weiss <krewecherl@gmail.com> - 2012-06-20 02:09 +0200
    Re: Function Objects Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-06-20 15:43 +0200
    Re: Function Objects Stefan Weiss <krewecherl@gmail.com> - 2012-06-20 17:29 +0200

csiph-web