写"班级"在JavaScript中

时间:2017-03-06 14:21:32

标签: javascript class module-pattern

bobince写了一篇很好的帖子,如何写"类"在JavaScript中:How to "properly" create a custom object in JavaScript?

正如文章所说,有两种方法可以在JavaScript中编写类: - 关闭方式 - 原型方式

但是也可以使用模块模式编写类,不是吗?我很困惑,因为有很多关于JavaScript的信息,其中一些是矛盾的。

带模块模式的示例类(?):

var MyClass = function () {
    // Private variables
    var firstName;
    var secondName;

    // Public functions
    return {
        getFullName: function () {
            return (this.firstName + " " + this.secondName);
        },

        setFirstName: function (value) {
            this.firstName = value;
        },

        setSecondName: function (value) {
            this.secondName = value;
        },

        getFirstName: function (value) {
            return this.firstName;
        },

        getSecondName: function (value) {
            return this.secondName;
        }
    }
};



describe("test module", function () {

    it("Test instance", function () {
        var myInstance = new MyClass("Michael", "Jackson");

        expect(myInstance).not.toBeNull();
    });

    it("setter and getter", function () {
        var myInstance = new MyClass("Michael", "Jackson");

        myInstance.setFirstName("Michael");
        myInstance.setSecondName("Jackson");

        expect(myInstance.getFirstName()).toBe("Michael");
        expect(myInstance.getSecondName()).toBe("Jackson");
        expect(myInstance.getFullName()).toBe("Michael Jackson");
    });

    it("Test instances", function () {
        var myInstance1 = new MyClass();
        myInstance1.setFirstName("Michael");
        myInstance1.setSecondName("Jackson");

        var myInstance2 = new MyClass();
        myInstance2.setFirstName("Paris");
        myInstance2.setSecondName("Hilton");

        expect(myInstance1.getFullName()).toBe("Michael Jackson");
        expect(myInstance2.getFullName()).toBe("Paris Hilton");

        expect(myInstance1 != myInstance2).toBe(true);
    });
});

0 个答案:

没有答案