[英]Object.prototype pattern
我并不了解如何在类(es6)中使用Object.prototype模式;
我不确定这是我的代码,我以正确的方式使用了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/zh-CN/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
构造函数对象上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.