don't overwrite the prototype

This commit is contained in:
Harrison Shoff
2012-11-01 17:39:32 -07:00
parent 4c04d5c5d1
commit b2c7d3d0d3

View File

@@ -984,14 +984,12 @@
this.set('lightsaber', lightsaber);
}
Jedi.prototype = {
set: function(key, val) {
this[key] = val;
},
Jedi.prototype.set: function(key, val) {
this[key] = val;
};
get: function(key) {
return this[key];
}
Jedi.prototype.get = function(key) {
return this[key];
};
```
@@ -1000,7 +998,7 @@
## <a name='constructors'>Constructors</a>
- Assign the constructors prototype as an object. This saves us some typing. Also, the extra level of indentation acts as an indication that you are working on the prototype and not instance methods.
- Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!
```javascript
function Jedi() {
@@ -1008,15 +1006,6 @@
}
// bad
Jedi.prototype.fight = function fight() {
console.log('fighting');
};
Jedi.prototype.block = function block() {
console.log('blocking');
};
// good
Jedi.prototype = {
fight: function fight() {
console.log('fighting');
@@ -1026,21 +1015,28 @@
console.log('blocking');
}
};
// good
Jedi.prototype.fight = function fight() {
console.log('fighting');
};
Jedi.prototype.block = function block() {
console.log('blocking');
};
```
- Constructor methods should try to return `this`. This helps with method chaining which is often useful.
```javascript
// bad
Jedi.prototype = {
jump: function() {
this.jumping = true;
return true;
},
Jedi.prototype.jump = function() {
this.jumping = true;
return true;
};
setHeight: function(height) {
this.height = height;
}
Jedi.prototype.setHeight = function(height) {
this.height = height;
};
var luke = new Jedi();
@@ -1048,16 +1044,14 @@
luke.setHeight(20) // => undefined
// good
Jedi.prototype = {
jump: function() {
this.jumping = true;
return this;
},
Jedi.prototype.jump = function() {
this.jumping = true;
return this;
};
setHeight: function(height) {
this.height = height;
return this;
}
Jedi.prototype.setHeight = function(height) {
this.height = height;
return this;
};
var luke = new Jedi();
@@ -1075,14 +1069,12 @@
this.name = options.name || 'no name';
}
Jedi.prototype = {
getName: function getName() {
return this.name;
},
Jedi.prototype.getName = function getName() {
return this.name;
};
toString: function toString() {
return 'Jedi - ' + this.getName();
}
Jedi.prototype.toString = function toString() {
return 'Jedi - ' + this.getName();
};
```
@@ -1254,6 +1246,7 @@
## <a name='contributors'>Contributors</a>
- [Dave Augustine](//github.com/daveaugustine) || [@daveaugustine](//twitter.com/daveaugustine)
- [Matt Baker](//github.com/reissbaker) || (@reissbaker)(//twitter/reissbaker)
## <a name='license'>License</a>