Hands-On Full Stack Web Development with Aurelia
上QQ阅读APP看书,第一时间看更新

Prototyped

JavaScript uses prototypes instead of classes for inheritance. It is possible to emulate all OOP characteristics using just prototypes:

function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}

var diego = new Person('Diego', 'Arguelles', 26)
diego.nationality = 'Peruvian'
console.log(diego)
// Person {firstName: "Diego", lastName: "Arguelles", age: 26, nationality: "Peruvian"}

Person.prototype.career = 'Engineering'
console.log(diego.career) // Engineering

That being said, what is exactly a prototype? Different from objects, one prototype does not have a closed structure. In objects, we define standard properties and we just have these properties for work, since JavaScript is not completely an object-oriented language, we have the advantage to add, remove, or change properties and values of our prototypes depending on our needs.

We can modify prototype attributes at runtime. Note that even if you can modify any prototype, you should only modify yours. If you modify standard prototypes (for example, the  array prototype) you will encounter very weird bugs in your application.