次の方法で共有


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.

Comments

  • Anonymous
    April 26, 2007
    The comment has been removed
  • Anonymous
    April 26, 2007
    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 :)