面向对象和非面向对象的javascript之间的区别

时间:2013-05-01 11:08:42

标签: javascript

在与数字公司的一位建筑师会面时,我被问到面向对象和非面向对象的javascript之间有什么区别。

不幸的是,我无法正确回答这个问题,我只是回答说我认为javascript只是面向对象的语言。

我知道javascript的面向对象设计你可以使用普通的oop程序,例如polymorphism。

我们怎么看待这个?是否有这样的差异,我们可以将两者分开吗?

2 个答案:

答案 0 :(得分:3)

大多数面向对象的语言都可以以非OO方式使用。 (大多数非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程序。

这是OO形式的相同内容:

// 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]中会更好。)

答案 1 :(得分:0)

完全有可能在不声明类或原型的情况下编写Javascript的工作代码。当然,你使用对象,因为API和DOM都是由它们组成的。但你真的不需要以OO的方式思考。

但是也可以以完全OO的方式编写Javascript代码 - 创建大量的类/原型,利用多态性和继承,根据对象之间传递的消息设计行为,等等。

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