1

I know there is a lot of material available on using prototypes but there seem to be a lot of different suggested methods and I'm trying to find mine. I'm really just looking for feedback on the structure below and if you'd see anything issues with it. Thanks in advance.

function Class(){}

Class.prototype = {
    MethodOne: function() {

    },
    MethodTwo: function() {

    },
    MethodThree: function() {

   }
}
2
  • 3
    To answer your question, it looks syntax-correct. But it all depends on your use case. Are you trying to make this into an Object that you would eventually inherit to other objects? Commented Dec 14, 2012 at 18:47
  • One you figure out what is your objective with prototypes, update your question with details and notify in comments. Commented Dec 14, 2012 at 18:52

2 Answers 2

2

Overall perfect! This is how I create my classes too. Here are a few minor edits:

function Class() {
   return this;
}

Class.prototype = {
    methodOne: function() {

    },
    methodTwo: function() {

    },
    methodThree: function() {

   }
}

1) Changed the method names to start with lowercase. Just for convention.
2) Made your constructor return this (the newly create object).
3) Once you have created the Class you can use it like:

 var obj = new Class();  
 obj.methodOne();  
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to put return this in constructor. It's a default behaviour. But it's good to know, that constructor can return different object than this but it cannot return primitive value.
2

You're example is really simple and syntax correct. However, I'd like to share my thoughts with you.

First of all, you completely replace prototype object of your Class constructor. It's fine, but you lose reference to constructor from objects created with Class. Using you code:

var a = new Class();
a.constructor; // => function Object() { [native code] }

Wouldn't it be better if constructor property points to Class as it's a real constructor? To fix it, you need to add constructor property to Class prototype. Like: Class.prototype.constructor = Class.

Secondly, I usually see object methods starting from lower case letter. It's rather a convention, but that's how all native object's methods are defined. For instance, look at methods defined in default Date object (Date.prototype.*). All of them start with lower case letter.

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.