+ 1
Who knows a simpler approach to defining object methods?
I can't seem to understand how to define methods. I'm trying to create a method where the parentheses of the objects can be used in it. The description in the course is confusing to me. Please help
2 ответов
+ 2
Do these examples help? JavaScript supports many ways to define class-like things and methods.
Example 1:
function contact(name, number) {
this.name = name;
this.number = number;
this.print = function() {
console.log(`${this.name}: ${this.number}`);
};
}
var a = new contact("David", 12345);
var b = new contact("Amy", 987654321)
a.print();
b.print();
Example 2:
class Contact {
constructor(name, number) {
this.name = name;
this.number = number;
}
print() {
console.log(`${this.name}: ${this.number}`);
}
}
var a = new Contact("David", 12345);
var b = new Contact("Amy", 987654321);
a.print();
b.print();
+ 1
Thanks Josh. Those examples of yours were actually the project I had problems with.