2013-05-01 163 views
0

在與數字公司的一位架構師的會議中,有人問我面向對象和非面向對象的JavaScript有什麼區別。面向對象和非面向對象之間的區別javascript

不幸的是,我無法正確回答這個問題,我只是回答我以爲JavaScript只是面向對象的語言。

我知道面向對象的JavaScript設計,你可以有通常的操作,如多態。

我們如何看待這件事?有沒有這樣的差異,我們可以將兩者分開嗎?

回答

2

大多數面向對象的語言可以以非OO方式使用。 (大多數非OO語言都可以在一個面向對象的方式使用爲好,走到那,你就必須作出努力。)JavaScript是特別適合於程序性和功能性的方式來使用(而且也非常適合以各種OO方式使用)。這是一種非常非常靈活的語言。

例如,這裏有寫一些東西,需要處理有關人員的信息兩種方式,說他們是多麼老:

程序:

// Setup 
function showAge(person) { 
    var now = new Date(); 
    var years = now.getFullYear() - person.born.getFullYear(); 
    if (person.born.getMonth() < now.getMonth()) { 
     --years; 
    } 
    // (the calculation is not robust, it would also need to check the 
    // day if the months matched -- but that's not the point of the example) 
    console.log(person.name + " is " + years); 
} 

// Usage 
var people = [ 
    {name: "Joe",  born: new Date(1974, 2, 3)}, 
    {name: "Mary",  born: new Date(1966, 5, 14)}, 
    {name: "Mohammed", born: new Date(1982, 11, 3)} 
]; 
showAge(people[1]); // "Mary is 46" 

這不是特別面向對象的。假設它知道它們的屬性名稱,showAge函數作用於給定的對象。這有點像一個在struct s上工作的C程序。

下面是一個面向對象的形式同樣的事情:

// Setup 
function Person(name, born) { 
    this.name = name; 
    this.born = new Date(born.getTime()); 
} 
Person.prototype.showAge = function() { 
    var now = new Date(); 
    var years = now.getFullYear() - this.born.getFullYear(); 
    if (this.born.getMonth() > now.getMonth()) { 
     --years; 
    } 
    // (the calculation is not robust, it would also need to check the 
    // day if the months matched -- but that's not the point of the example) 
    console.log(person.name + " is " + years); 
}; 

// Usage 
var people = [ 
    new Person("Joe",  new Date(1974, 2, 3)), 
    new Person("Mary",  new Date(1966, 5, 14)), 
    new Person("Mohammed", new Date(1982, 11, 3)) 
]; 
people[1].showAge(); // "Mary is 46" 

這是更面向對象的。數據和行爲都由構造函數Person定義。如果你想,你甚至可以封裝(比如說)born的值,這樣它就不能從其他代碼中訪問。 (封裝時JavaScript是「好的」(使用閉包);封裝[在two相關ways]在下一個版本中會更好。)

0

完全有可能在沒有聲明類或原型的情況下編寫一段Javascript代碼。當然你會使用對象,因爲API和DOM是由它們組成的。但你並不需要以OO的方式思考。

但是,也可以以徹底的OO方式編寫Javascript代碼 - 創建大量類/原型,利用多態性和繼承性,根據對象之間傳遞的消息設計行爲等等。

我懷疑這是面試官希望從你那裏得到的區別。