Not signed in (Sign In)

SkillShare - A place to discuss Web Standards and Web Design topics

Categories

Vanilla 1.1.9 is a product of Lussumo. More Information: Documentation, Community Support.

    •  
      CommentAuthorSpookyET
    • CommentTimeJul 21st 2006 edited
     permalink
    Would not it make sense to write safer JavaScript code without using public fields "foo.bar" and ugly setter/getter "foo.getBar(); foo.setBar(value);"?
    .NET style properties can be done in JavaScript with naming conventions and an if statement.

    C#
    ---------------------------
    class ConnectionInfo
    {
    private uint port;

    public uint Port
    {
    get
    {
    return port;
    }
    set
    {
    port = value;
    }
    }

    public override string ToString()
    {
    return string.Format("Port: {0}", port);
    }
    }

    ConnectionInfo connectionInfo = new ConnectionInfo();
    uint port = connectionInfo.Port // Get the port.
    connectionInfo.port = 80; // Set the port.
    Console.WriteLine(connectionInfo.ToString());

    JavaScript
    --------------------------------------------
    function ConnectionInfo()
    {
    var port = 0; // private field

    // Name a property with a noun.
    this.port = function()
    {
    if (arguments.length == 0)
    {
    return port;
    }
    else
    {
    if (arguments[0] >= 0 && arguments[0] <= 65535)
    {
    port = arguments[0];
    }
    else
    {
    throw "ArgumentOutOfRangeException: value must be between 0 and 65535";
    }
    }
    }

    // Name a function with a verb.
    this.toString = function()
    {
    return "Port: " + port;
    }
    }

    // Usage
    var connectionInfo = new ConnectionInfo();
    var port = connectionInfo.port(); // Get the port.
    connectionInfo.port(80); // Set the port;
    connectionInfo.toString(); // Call a method.
    •  
      CommentAuthorSpookyET
    • CommentTimeJul 21st 2006 edited
     permalink
    Notice that JavaScript 1.5, supported by Firefox, does have properties support.


    function ConnectionInfo()
    {
    var self = this;

    this.port = {
    _port: 0,
    port getter: function()
    {
    return _port
    },
    port setter: function(value)
    {
    if (value >= 0 && value <= 65535)
    {
    _port = value;
    }
    else
    {
    throw "ArgumentOutOfRangeException: value must be between 0 and 65535";
    }
    }
    }

    // Name a function with a verb.
    this.toString = function()
    {
    return "Port: " + self.port;
    }
    }


    // Usage
    var connectionInfo = new ConnectionInfo();
    connectionInfo.port = 80; // Set the port to 80;'
    console.info(connectionInfo.port); // Get the port.
    connectionInfo.toString(); // Call a method.
Add your comments
    Username Password
  • Format comments as (Help)