2016年5月4日 星期三

Javascript的封裝

封裝1

宣告+定義

function Female(name, age) {
    this.name = name;
    var age = age;
    this.sayAge = function() {
        if (age > 18) {
            console.log(this.name + ' is 18.');
        }
        else
        {
            console.log(this.name + ' is ' + age + '.');
        }
    };
};

呼叫執行

var mary = new Female('Mary', 16);
mary.sayAge();

var susan = new Female('Susan', 36);
susan.sayAge();

顯示

Mary is 16.
Susan is 18.

封裝2

宣告+定義

function Female(name, age) {
    this.name = name;
    var age = age;
    this.sayAge = function() {
        if (age > 18) {
            console.log(this.name + ' is 18.');
        }
        else
        {
            //sayRealAge   is a function
            //sayRealAge() is a function return value
            console.log(this.name + ' is ' + sayRealAge() + '.');
        }
    };
    
    var sayRealAge = function() {
     return age;
    };
};

呼叫執行

var mary = new Female('Mary', 16);
mary.sayAge();

var susan = new Female('Susan', 36);
susan.sayAge();

顯示

Mary is 16.
Susan is 18.

沒有留言:

張貼留言