gpt4 book ai didi

javascript - 面向对象和非面向对象 JavaScript 的区别

转载 作者:行者123 更新时间:2023-11-28 20:31:17 25 4
gpt4 key购买 nike

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

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

我知道通过 JavaScript 的面向对象设计,您可以拥有常见的 oop 过程,例如多态性。

我们对此有何看法?有这样的区别吗?我们可以将两者分开吗?

最佳答案

大多数面向对象语言都可以以非 OO 方式使用。 (大多数非 OO 语言也可以以 OO 方式使用,说到这一点,你只需要付出努力。)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 ]。)

关于javascript - 面向对象和非面向对象 JavaScript 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com