您想查找是否有一个用该字符串实例化的名词类?-@plalx
是的,我愿意-@pi1yau1u
在这种情况下,您可以使用地图来存储所有新创建的实例并实现一个 API,该 API 允许您按名称检索它们或检索整个列表。我还实现了一个findIn
实例方法,它将返回指定字符串中该名词的索引,如果没有找到,则返回 -1。
演示
var Noun = (function (map) {
function Noun(name) {
name = name.toLowerCase();
var instance = map[name];
//if there's already a Noun instanciated with that name, we return it
if (instance) return instance;
this.name = name;
//store the newly created noun instance
map[name] = this;
}
Noun.prototype.findIn = function (s) {
return s.indexOf(this.name);
};
Noun.getByName = function (name) {
return map[name.toLowerCase()];
};
Noun.list = function () {
var m = map, //faster access
list = [],
k;
for (k in m) list.push(m[k]);
return list;
};
return Noun;
})({});
new Noun('table');
new Noun('apple');
//retrieve a noun by name
console.log('retrieved by name :', Noun.getByName('table'));
//check if a string contains some noun (without word boundaries)
var s = 'I eat an apple on the couch.';
Noun.list().forEach(function (noun) {
if (noun.findIn(s) !== -1) console.log('found in string: ', noun);
});