将参数传递给模块的匿名函数

时间:2013-11-09 17:12:10

标签: javascript jquery module

$(document).ready(function () {
    var patient = (function (options) {
        var age = options.age;
        var name = options.name;

        function getName() {
            return this.name;
        }

        function setName(val) {
            name = val;
        }

        function getAge() {
            return this.age;
        }

        function setAge(val) {
            age = val;
        }
        return {
            getAge: getAge,
            setAge: setAge,
            getName: getName,
            setName: setName
        }
    })();
});

我意识到我在这里的例子中从未传递任何选项。 如果我尝试执行patient.setAge('100')然后console.log(patient.getAge())之类的操作,则会收到错误消息cannot read property Age of undefined。我试图获得的首要主题是在一个模块中,我如何模拟consturctors来实例化一个新的患者对象,同时保持私有变量和所有爵士乐的所有OOP优点。

我在这里看到了一些模块模式中构造函数的例子,我对它们的理解并不是很好。一般来说,在模块中有一个构造函数是个好主意吗?它的主要目的是否与基于类的语言相似?

2 个答案:

答案 0 :(得分:1)

这是一个构造函数:

function Patient(options) {
    options = options || {};

    this.age = options.age;
    this.name = options.name;
}

$(document).ready(function () {
    var patient = new Patient();
});

如果需要,可以将其放在模块中。你不应该做的是提供getter和setter,特别是那些不做任何事情的人。如果您通过两个属性公开变量来获取和设置它,那么它应该只是一个属性。

答案 1 :(得分:1)

试试这个

   function Patient (options) {
        options = options || {};
        var age = options.age;
        var name = options.name;

        function getName() {
            return name;
        }

        function setName(val) {
            name = val;
        }

        function getAge() {
            return age;
        }

        function setAge(val) {
            age = val;
        }
        return {
            getAge: getAge,
            setAge: setAge,
            getName: getName,
            setName: setName
        }
    });  // pass empty object 

$(document).ready(function () {
    var p1 =  new Patient({});
   var p2 =  new Patient();
    var p3 =  new Patient({age:20});
     var p4 =  new Patient({name:"abcd"});
    var p5 =  new Patient({age:21, name:"abcd"});
});