在与数字公司的一位架构师会面时,有人问我面向对象的javascript和非面向对象的javascript有什么不同。
不幸的是,我无法正确地回答这个问题,我只是回答我认为javascript只是一种面向对象的语言。
我知道在面向对象的javascript设计中,你可以使用常见的oop过程,比如多态性。
我们对此有何看法?有这样的区别吗?我们能把两者分开吗?
发布于 2013-05-01 19:16:06
大多数面向对象的语言都可以以非面向对象的方式使用。(大多数非面向对象的语言也可以以面向对象的方式使用,要做到这一点,你只需要努力。)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表单中的相同内容:
// 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中]。)
发布于 2013-05-01 19:14:19
完全可以在不声明类或原型的情况下编写Javascript的工作部分。当然,您可以使用对象,因为API和DOM都是由它们组成的。但是你并不真的需要以面向对象的方式去思考。
但也可以用完全面向对象的方式编写Javascript代码--创建大量的类/原型,利用多态性和继承,根据对象之间传递的消息设计行为,等等。
我怀疑这就是面试官希望从你那里得到的区别。
https://stackoverflow.com/questions/16317025
复制相似问题