For the example you give, you should use the prototype approach. In general, it depends. The main advantage of the first approach (initializing methods in the constructor) is that you can take advantage of closures by making use of local variables defined within the constructor in your methods. These variables are not directly accessible outside the constructor function so are effectively "private", meaning your API is cleaner than if these variable were instead defined as properties of the object. Some general rules of thumb:
- If your methods do not use local variables defined in your constructor (your example doesn't), then use the prototype approach.
- If you're creating lots of
Dog
s, use the prototype approach. This way, all "instances" (i.e. objects created by the Dog
constructor) will share one set of functions, whereas the constructor way, a new set of functions is created every time the Dog
constructor is called, using more memory.
- If you're creating a small number of
Dog
s and find that using local, "private" variables in your constructor improves your code, this may be the better approach. Use your judgment and do some benchmarks if performance or memory consumption are major concerns.
It is possible to use a hybrid approach whereby only methods that need access to local private constructor variables are defined in the constructor while other methods are assigned to the prototype.
For example, the code below uses a local variable in the constructor to keep track of the number of times this dog has barked while keeping the actual number private, so the barking-related methods are defined inside the constructor. Tail wagging does not require access to the number of barks, therefore that method can be defined on the prototype.
var Dog = function(name) {
this.name = name;
var barkCount = 0;
this.bark = function() {
barkCount++;
alert(this.name + " bark");
};
this.getBarkCount = function() {
alert(this.name + " has barked " + barkCount + " times");
};
};
Dog.prototype.wagTail = function() {
alert(this.name + " wagging tail");
};
var dog = new Dog("Dave");
dog.bark();
dog.bark();
dog.getBarkCount();
dog.wagTail();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…