JavaScript库模式 [英] JavaScript library pattern

查看:112
本文介绍了JavaScript库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图找出创建JavaScript库(类)的基本模式。我想这样做,它不会用一堆垃圾污染全局命名空间,但允许类有实例变量和修改这些实例变量的公共方法。

I'm trying to figure out the basic pattern for creating a JavaScript library (class). I want to do it in such a way that it doesn't pollute the global namespace with a bunch of junk, but allowing for the class to have instance variables and public methods that modify those instance variables.

考虑下面的玩具示例。我想要一个类 Foo 。它应该包含一个实例成员, bar ,它是一个数字。应该有一个 Foo 的构造函数,它需要一个数字,并用该数字初始化其实例 bar 。应该有一个实例方法,我可以调用 Foo 对象来修改 bar 。也许使用库的代码如下所示:

Consider the following toy example. I want to make a class Foo. It should contain an instance member, bar, which is a number. There should be a constructor for Foo that takes a number and initializes its instance bar with that number. There should be an instance method that I can call on a Foo object to modify bar. Maybe the code that uses the library looks like this:

var foo1 = new Foo(1);
var foo2 = new Foo(2);
console.log(foo1.bar); // should print "1"
console.log(foo2.bar); // should print "2"
foo2.changeBar(42);
console.log(foo1.bar); // should print "1"
console.log(foo2.bar); // should print "42"

结果 foo.js 将被Web应用程序使用,因此通过HTML中的脚本标签来包含。

The resultant foo.js would be used by a Web app and therefore included via a script tag in the HTML.

我已经用Google进行了一些搜索,但是尚未找到如何设计JavaScript类(用作库)的简单,简单的概述。

I've done a bit of searching with Google but I have yet to find a single, concise, generic outline of how to design a JavaScript class (used as a library).

推荐答案

(function () {
    Foo = function (num) {
         this.changeBar(num);
    };

    var privateMethod = function (x) {
        if (this.bar === 999) {
            this.bar = x;
        }
    };

    Foo.prototype.changeBar = function (num) {
        this.bar = num;
        privateMethod.call(this, 1);
    };

}());

这是最简单的方法。您不需要将定义包含在闭包中,更多的是样式的东西。

That is the simplest way of doing it. You don't need to include the definition in a closure, more of a style thing.

这篇关于JavaScript库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆