1
$(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
        }
    })();
});

I realize that I'm never passing any options in my example here. If I try to do something like patient.setAge('100') and then console.log(patient.getAge()) I get an error saying cannot read property Age of undefined. The overarching theme that I'm trying to get at is within a module, how can I emulate consturctors to instantiate a new patient object while keeping all the OOP goodness of private variables and all that jazz.

I've seen some examples of constructors in a module pattern on here and I haven't understood them very well. Is it a good idea in general to have a constructor in a module? Is its main purpose similarity with class-based languages?

4

2 に答える 2

1

これはコンストラクタです:

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

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

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

必要に応じて、モジュール内に配置できます。すべきでないことは、ゲッターとセッター、特に何もしないものを提供することです。2 つのプロパティを介して変数を公開して取得および設定する場合は、1 つのプロパティのみにする必要があります。

于 2013-11-09T17:22:27.227 に答える
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"});
}); 
于 2013-11-09T17:25:00.253 に答える