JavaScript Object Prototype Pro Trick
In JavaScript, every object has a prototype, which is an object that serves as a blueprint for the object. The prototype object contains methods and properties that are shared among all instances of the object.
To create an object in JavaScript, you can use the object literal syntax, which looks like this:
let myObject = {
// properties and methods go here
};
To set the prototype of an object, you can use the Object.create() method. For example, you could create a Person object with a name property and a greet() method like this:
let Person = {
name: '',
greet: function() {
console.log('Hello, my name is ' + this.name);
}
};
let person1 = Object.create(Person);
person1.name = 'Alice';
person1.greet(); // logs 'Hello, my name is Alice'
In this example, we create a Person object with two properties: name and greet(). We then create a new object person1 using the Object.create() method and set its prototype to Person. Finally, we set the name property of person1 to ‘Alice’ and call its greet() method, which logs “Hello, my name is Alice” to the console.
Note that when you call a method on an object, JavaScript first looks for the method on the object itself. If the method isn’t found, it then looks for it on the object’s prototype, and so on up the prototype chain until it finds the method or reaches the end of the chain (which is the Object.prototype object).