Objects in JavaScript

本文將簡單介紹 Java Script 傳統的程序性功能撰寫方式,以及兩種模擬OOP的物件撰寫方式

Procedural Code

var person = new Object();
person.Name = "Dino";
person.LastName = "Esposito";
person.BirthDate = new Date(1992,10,17)
person.getAge = function() {
var today = new Date();
var thisDay = today.getDate();
var thisMonth = today.getMonth();
var thisYear = today.getFullYear();
var age = thisYear-this.BirthDate.getFullYear()-1;
if (thisMonth > this.BirthDate.getMonth())
age = age +1;
else
if (thisMonth == this.BirthDate.getMonth() &&
thisDay >= this.BirthDate.getDate())
age = age +1;
return age;
}

Using Closures -模擬OOP , method 1

var Person = function(name, lastname, birthdate)
{
this.Name = name;
this.LastName = lastname;
this.BirthDate = birthdate;
this.getAge = function() {
var today = new Date();
var thisDay = today.getDate();
var thisMonth = today.getMonth();
var thisYear = today.getFullYear();
var age = thisYear-this.BirthDate.getFullYear()-1;
if (thisMonth > this.BirthDate.getMonth())
age = age +1;
else
if (thisMonth == this.BirthDate.getMonth() &&  thisDay >= this.BirthDate.getDate())
age = age +1;
return age;
}
}

Using Prototypes -模擬OOP , method 1

// Pseudo constructor
var Person = function(name, lastname, birthdate)
{
this.initialize(name, lastname, birthdate);
}
// Members
Person.prototype.initialize(name, lastname, birthdate)
{
this.Name = name;
this.LastName = lastname;
this.BirthDate = birthdate;
}
Person.prototype.getAge = function()
{
var today = new Date();
var thisDay = today.getDate();
var thisMonth = today.getMonth();
var thisYear = today.getFullYear();
var age = thisYear-this.BirthDate.getFullYear()-1;
if (thisMonth > this.BirthDate.getMonth())
age = age +1;
else
if (thisMonth == this.BirthDate.getMonth() &&
thisDay >= this.BirthDate.getDate())
age = age +1;
return age;
}

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s