2013-05-01 149 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代码 - 创建大量类/原型,利用多态性和继承性,根据对象之间传递的消息设计行为等等。

我怀疑这是面试官希望从你那里得到的区别。