对象原型模式



我不明白如何将 Object.prototype 模式与类一起使用 (es6(;

这是我的代码,我不确定,我是否以正确的方式使用了Object.prototype。

class Course{ 
constructor(title, author) {
this.title = title;
this.author = author;
}
}

Course.prototype.toString = function (arguments) {
console.log(this.title + "... Author: " + this.author);
};
var course_1 = new Course("Bootstrap 4", "Paul");
var course_2 = new Course("Design Patterns", "Paul");
course_1.toString();
course_2.toString();
}

我应该使用不同的东西吗?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

ES6 类是语法糖,它允许您避免使用 Object.prototype,您只需定义这样的类方法:

class Course{ 
constructor(title, author) {
this.title = title;
this.author = author;
}
toString(arguments) {
console.log(this.title + "... Author: " + this.author);
}
}

使用es6 类编写应用程序是直接使用原型模式进行开发的替代方法

在引擎盖下,es6 类实际上编译为原型结构。但是 es6 类往往更容易阅读,当你的应用程序变得非常大时,这可能会让一切变得不同。

在您的情况下,您可以将要附加到原型的方法放在您创建的类中。这看起来更类似于经典的面向对象编程,正如您在C++或Java中看到的那样。

你可以在这里阅读更多关于 MDN 上的 es6 类的信息

根据您的示例:

class Course { 
constructor(title, author) {
this.title = title;
this.author = author;
}
toString(arguments) {
console.log(this.title + "... Author: " + this.author);
}
}
var course_1 = new Course("Bootstrap 4", "Paul");
var course_2 = new Course("Design Patterns", "Paul");
course_1.toString();
course_2.toString();

在以下代码中:

class Course {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
Course.prototype.toString = function(arguments) {
console.log(this.title + "... Author: " + this.author);
};
var course_1 = new Course("Bootstrap 4", "Paul");
var course_2 = new Course("Design Patterns", "Paul");
course_1.toString();
course_2.toString();

类只不过是类似于构造函数功能的语法糖。我们可以在以下示例中更深入地观察这一点:

class Person {
}
console.log(typeof Person);

类 Person 实际上是一个构造函数对象。就像普通的构造函数一样,我们可以通过在原型对象上放置属性来扩展原型。

所以在你的例子中:

Course.prototype.toString = function(arguments) {
console.log(this.title + "... Author: " + this.author);
};

在后台实际发生的事情是,您将一个名为 toString 的属性放在Course构造函数对象上。

最新更新