-1

I do not understand quite completely how to apply constructors on this object creation method:


var MyObject = {
   ...
};

I know that you can do:


var MyObject = new Object();
MyObject.prototype.constructor = function(props)
{
  ...
}

or...


function MyObject(prop1, prop2)
{
 this.prop1 = prop1;
 ...
}

Can I do something like this?


var MyObject = {
   MyObject: function(prop1, prop2)
   {
     ...
   }
}

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting "MyObject.prototype is undefined" when I attempt to define the constructor by using MyObject.prototype.constructor = function() ... what could be wrong?
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.
Yeah, I figured out it would be simpler that way. Thanks a lot for you help!
0

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.

Comments

0
var MyObject = new Object();
MyObject.prototype.constructor = function(props)
{
    ...
}

is the same as

var MyObject = {};
MyObject.prototype.constructor = function(props)
{
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.