views:

159

answers:

3
+1  A: 

Example from here

Creating constructors

To write your own constructors, you use the this keyword within the constructor to refer to the newly-created object. The constructor initializes the object.

In the example below:

The make7Table constructor creates a multiplication table for number 7 The size property is introduced to keep track of the number of elements The value of each element is initialized

function make7Table(numElements)
{
    this.size = numElements;
    var cnt;
    for(cnt = 0; cnt < numElements; cnt++)
    {
        this[cnt] = cnt*7;
    }
}

// Use the constructor to create and initialize an array.
myArray = new make7Table(10);
document.write(myArray[5]);
document.write("This table has " + myArray.size + " elements");

To run the code, paste it into JavaScript Editor, and click the Execute button. myArray[5] retrieves the element with the value of 5*7 = 35.

gmcalab
+1  A: 
var MyObject = new Object();
MyObject.prototype.constructor = function(props)
{
    ...
}

is the same as

var MyObject = {};
MyObject.prototype.constructor = function(props)
{
    ...
}
Gabriel McAdams
+1  A: 

No, you can't, that would simply create a (static) method on MyObject -- MyObject.MyObject. In JavaScript, a constructor is the class. Class methods and properties are created either inside the constructor using this. or by adding to the prototype (outside of the constructor) using MyClass.prototype.. You can think of "objects" in JavaScript as static classes.

Renesis
I'm getting "MyObject.prototype is undefined" when I attempt to define the constructor by using MyObject.prototype.constructor = function() ... what could be wrong?
Joel Alejandro
I wondered about this when you made your first post. Functions/Classes are a mysterious world but I will try to explain what I think is happening. An "Object" (`var o = new Object();`) is not a Function, therefore has no `prototype`. You may be able to achieve what you want by defining it as a `new Function()` instead, however, I would just use `function o () { ... }` then add "members" to the class after that definition, using the prototype.
Renesis
Yeah, I figured out it would be simpler that way. Thanks a lot for you help!
Joel Alejandro