首页 \ 问答 \ 将模块模式与Prototype相结合(Combining Module pattern with Prototype)

将模块模式与Prototype相结合(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没有在构造函数中定义。 我该如何解决?


I am trying to encapsulate some methods by using module pattern. I am also trying to avoid new function definitions on new object creation by using a prototype. The problem is I have to implement a constructor and I couldn't figure how. My code:

 // 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

Running

Anagram.new('ant').match(['tan', 'stand', 'at'])

Fails with

TypeError: Object #<Object> has no method 'sort'

And I understand why, sort is not defined in the constructor. How can I fix it?


原文:https://stackoverflow.com/questions/21191599
更新时间:2023-05-21 21:05

最满意答案

首先选择表格,然后查找子行:

jQuery("table").find("tr:odd").css("background-color","#f5f5f5");

http://jsfiddle.net/mblase75/xgQ8Q/

Vega的答案使用相同的方法,使用更少的字符。


Start by selecting the tables, then finding the child rows:

jQuery("table").find("tr:odd").css("background-color","#f5f5f5");

http://jsfiddle.net/mblase75/xgQ8Q/

Vega's answer uses the same approach with fewer characters.

相关问答

更多