简体   繁体   English

使用方法创建javascript对象?

[英]Create javascript object with methods?

I need to create a "parser" library and want to pass in the source document only one time.我需要创建一个“解析器”库,并且只想传入一次源文档。 How can I supply the source document and store it within the javascript object so I can call methods on the document?如何提供源文档并将其存储在 javascript 对象中,以便我可以调用文档上的方法?

This is what I'm trying, but it feels really messy... especially with the this keyword everywhere:这就是我正在尝试的,但感觉真的很混乱……尤其是到处都是this关键字:

'use strict';

var reader = function (info) {

    this.doc = info;

    this.getNode = function (name) {
        var nodes = this.doc.items.filter(function (item) {
            return (item.name.toUpperCase() == name.toUpperCase());
        });
        return (nodes.length == 1)
            ? nodes[0]
            : null;
    };

    this.getItems = function (name) {
        var node = this.getNode(name);
        return (node ? node.items : []);
    };

    return this;
};

module.exports = reader;

My goal is to use this reader object in other areas of my app, like this:我的目标是在我的应用程序的其他区域使用这个阅读器对象,如下所示:

var infoDoc = loadFromFile();   // Loads the file from disk

var reader = require('./reader')(infoDoc);

var items = reader('widgets');

Thanks, in advance.提前致谢。

Judging from your usage, you are using the factory pattern.从你的使用情况来看,你使用的是工厂模式。 For such a pattern, using this is unnecessary (since in javascript the basic factory pattern isn't constructor based).对于这样的模式,使用this是不必要的(因为在 javascript 中,基本工厂模式不是基于构造函数的)。 A simple way to implement it is like:一个简单的实现方法是这样的:

'use strict';

var reader = function (info) {

    var getNode = function (name) {
        var nodes = info.items.filter(function (item) {
            return (item.name.toUpperCase() == name.toUpperCase());
        });
        return (nodes.length == 1)
            ? nodes[0]
            : null;
    };

    var getItems = function (name) {
        var node = getNode(name);
        return (node ? node.items : []);
    };

    // return a map of the functions you want to expose.
    return {
        getItems: getItems,
        getNode: getNode
    };
};

module.exports = reader;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM