標籤:javascript
在原型對象上定義方法,而不是用新對象重寫它。重寫使繼承變為不可能:重設原型將重寫整個基類.
function Jedi() {console.log('new jedi');}// badJedi.prototype = {fight: function fight() {console.log('fighting');},block: function block() {console.log('blocking');}};// goodJedi.prototype.fight = function fight() {console.log('fighting');};Jedi.prototype.block = function block() {console.log('blocking');};<strong></strong>
關於JavaScript中的prototype可參見 http://www.w3school.com.cn/jsref/jsref_prototype_array.asp
方法應該返回this,有利於構成方法鏈
// badJedi.prototype.jump = function() {this.jumping = true;return true;};Jedi.prototype.setHeight = function(height) {this.height = height;};var luke = new Jedi();luke.jump(); // => trueluke.setHeight(20); // => undefined// goodJedi.prototype.jump = function() {this.jumping = true;return this;};Jedi.prototype.setHeight = function(height) {this.height = height;return this;};var luke = new Jedi();luke.jump().setHeight(20);
寫一個自訂的toString()方法是可以的,只要確保它能正常運行並且不會產生副作用
function Jedi(options) {options || (options = {});this.name = options.name || 'no name';}Jedi.prototype.getName = function getName() {return this.name;};Jedi.prototype.toString = function toString() {return 'Jedi - ' + this.getName();};
Genesis 1:17 And God set them in the firmament of the heaven to give light upon the earth.
【筆記】JavaScript編碼規範- 建構函式