首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >面向对象和非面向对象javascript的区别

面向对象和非面向对象javascript的区别
EN

Stack Overflow用户
提问于 2013-05-01 19:08:42
回答 2查看 1.8K关注 0票数 0

在与数字公司的一位架构师会面时,有人问我面向对象的javascript和非面向对象的javascript有什么不同。

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

我知道在面向对象的javascript设计中,你可以使用常见的oop过程,比如多态性。

我们对此有何看法?有这样的区别吗?我们能把两者分开吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-01 19:16:06

大多数面向对象的语言都可以以非面向对象的方式使用。(大多数非面向对象的语言也可以以面向对象的方式使用,要做到这一点,你只需要努力。)JavaScript特别适合在过程性和函数性两种方式中使用(也非常适合在各种面向对象的方式中使用)。这是一种非常非常灵活的语言。

例如,这里有两种方法来编写一些需要处理关于人们的信息的东西,比如他们的年龄:

程序:

代码语言:javascript
复制
// 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上运行的C程序。

以下是OO表单中的相同内容:

代码语言:javascript
复制
// 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中]。)

票数 3
EN

Stack Overflow用户

发布于 2013-05-01 19:14:19

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16317025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档