Welcome to MSDN Blogs Sign in | Join | Help

SYSK 337: JavaScript – Should You Define Functions Inside a Prototype or Outside?

Yesterday’s post described three ways to extend an existing type.  It occurred to me that there is one more, slightly different mechanism, for defining a prototype function… you can think of it as Method 2-b.

 

Consider the following:

 

function TestClass(param1)

{

    this._param1 = param1;

       

    TestClass.prototype.get_param1 = function()

    {

        return this._param1;

    }

}

 

If you were to break (while debugging the code) and look at the CallStack window, the get_param1 function would be seen as ‘JScript anonymous function’.  While it may not be important if you break in the get_param1 function, it would certainly be a valuable piece of information if you’re debugging some code downstream called from get_param1.

 

To get the actual function name and not the ‘anonymous’, you can define it as follows:

 

function TestClass(param1)

{

    this._param1 = param1;                                                   

}                                             

function TestClass$get_param1()

{                   

    return this._param1;

}           

TestClass.prototype =

{

    get_param1: TestClass$get_param1

}  

 

In this case, you should see ‘TestClass$get_param1’ in the CallStack window…

 

 

It’s my understanding that Microsoft AJAX team defines functions inside a prototype for release versions of scripts to minimize script size, and outside a prototype to maximize debuggability in debug versions.

 

 

Published Thursday, April 26, 2007 5:02 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: SYSK 337: JavaScript – Should You Define Functions Inside a Prototype or Outside?

Thursday, April 26, 2007 6:00 PM by Bruce

Doesn't that blow away any existing stuff in the prototype?  Could you do something like this instead:

function TestClass(param1)

{

   this._param1 = param1;

   TestClass.prototype.get_param1 = function TestClass$get_param1()

   {

       return this._param1;

   }

}

# re: Reply to Bruce

Thursday, April 26, 2007 7:21 PM by irenak

You can use commans as a function separator, e.g.

TestClass.prototype =

{

   get_param1: TestClass$get_param1,

   set_param1: TestClass$set_param1

}  

Having said that, your solution would work as well :)

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker