1

我知道有很多关于使用原型的材料,但似乎有很多不同的建议方法,我正在尝试找到我的方法。我真的只是在寻找有关以下结构的反馈,如果您发现它有任何问题。提前致谢。

function Class(){}

Class.prototype = {
    MethodOne: function() {

    },
    MethodTwo: function() {

    },
    MethodThree: function() {

   }
}
4

2 回答 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();  
于 2012-12-14T19:21:11.300 回答
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.

于 2012-12-14T19:21:36.620 回答