[英]Combining Module pattern with Prototype
我試圖通過使用模塊模式來封裝一些方法。 我還嘗試通過使用原型來避免在創建新對象時使用新的函數定義。 問題是我必須實現一個構造函數,但我不知道怎么做。 我的代碼:
// constructor
function Anagram(original) {
this.original = original.toLowerCase()
this.sortedOriginal = this.sort(this.original)
}
// prototype as a module
Anagram.prototype = (function() {
function isAnagram(word) {
word = word.toLowerCase()
return this.original != word && sameLetters(word)
}
function sameLetters(word) {
return this.sortedOriginal === sort(word)
}
function sort(str) {
return str.split('').sort().join('')
}
return {
match: function(words) {
return words.filter(isAnagram, this)
}
}
}())
module.exports = Anagram
運行
Anagram.new('ant').match(['tan', 'stand', 'at'])
與失敗
TypeError: Object #<Object> has no method 'sort'
而且我明白為什么在構造函數中未定義sort
。 我該如何解決?
我創建了一個稱為augment
的庫,該庫將模塊模式與原型繼承相結合。 例如,你可以實現你的Anagram
“類”使用如下augment
:
var augment = require("augment");
var Anagram = module.exports = augment(Object, function () {
this.constructor = function (original) {
this.original = original.toLowerCase();
this.sortedOriginal = sort(this.original);
};
function isAnagram(word) {
word = word.toLowerCase();
return this.original !== word && sameLetters.call(this, word);
}
function sameLetters(word) {
return this.sortedOriginal === sort(word);
}
function sort(str) {
return str.split("").sort().join("");
}
this.match = function(words) {
return words.filter(isAnagram, this);
};
});
現在您可以按以下方式使用它:
new Anagram("ant").match(["tan", "stand", "at"]);
觀看演示: http : //jsfiddle.net/GbWXB/
編輯:如果您願意,可以將deflcass
用作augment
替代品:
function defclass(base, body) {
var uber = base.prototype;
var prototype = Object.create(uber);
var constructor = (body.call(prototype, uber), prototype.constructor);
constructor.prototype = prototype;
return constructor;
}
參見演示: http : //jsfiddle.net/sy4fz/
問題在於排序不是原型的屬性。 原型只有一個稱為match的屬性,可以對其進行修復-您需要對Anagram原型進行排序。 因此,當您使用“ match”函數返回對象文字時,該對象還需要一個“ sort”函數屬性。
return {
match: function(words) {
return words.filter(isAnagram, this)
},
sort: function(str) {
return str.split('').sort().join('')
}
}
因此,每個Anagram都從其原型繼承兩個函數,並且this.sort()有效。
但是,您的代碼還有其他一些問題。 您定義的不屬於成為原型的返回對象的一部分的函數(例如sameLetters)將不會綁定到正確的“ this”。 如果您希望他們為此獲得正確的值-他們還需要繼續使用原型,或者在調用它們時需要傳遞給他們對此的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.