How to Use JavaScript Prototype

In JavaScript, every function has a prototype property that can be used to add properties and methods to the function’s instance objects. Specifically, properties and methods can be added to the function’s instance objects by assigning values to the function’s prototype property.

For example, we can define a constructor and add methods to it in the following way:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

// 为Person构造函数的实例对象添加一个greet方法
Person.prototype.greet = function() {
  console.log("Hello, my name is " + this.name);
};

// 创建Person构造函数的实例
var person1 = new Person("Alice", 25);
var person2 = new Person("Bob", 30);

// 调用实例对象的greet方法
person1.greet(); //输出:Hello, my name is Alice
person2.greet(); //输出:Hello, my name is Bob

In the example above, we defined a constructor function called Person and added a greet method to its instance objects by assigning a value to its prototype property. By creating instances of the Person constructor function and calling the greet method on those instances, we can see that each instance object can access this method.

It is important to note that properties and methods added through the prototype are shared, meaning all instances created from the constructor will share these properties and methods.

bannerAds