JavaScript Prototype Details

JavaScript Prototype Details

1. Overview

1.1 What is a prototype?

In JavaScript , a function is an object of type Function that contains properties and methods. The prototype is a property of the Function type object.

The prototype property is included in the function definition, and its initial value is an empty object. In JavaScript, there is no primitive type defined for functions, so the prototype can be any type.

The prototype is used to save the shared properties and methods of the object. The properties and methods of the prototype do not affect the properties and methods of the function itself.

The sample code verification is as follows:

function fun() {
  console.log('function prototype')
}
console.log(fun.prototype) // {}

fun.prototype also returns an empty object, but this does not mean that there are no properties or methods in Object.prototype . These properties and methods are not enumerable. The sample code is as follows:

function fun() {
  console.log('function prototype')
}

console.log(fun.prototype) // {}
// Get all properties through Object.getOwnPropertyNames() console.log(Object.getOwnPropertyNames(fun.prototype)) // [ 'constructor' ]

Among them, the constructor attribute points to the reference of the constructor. The code is as follows:

// constructor property console.log(fun.prototype.constructor) // [Function: fun]

console.log(fun.prototype.constructor === fun) // true

1.2 Get the prototype

After understanding the concept and function of prototype, we need to obtain the prototype before operating it. There are two ways to obtain the prototype in JavaScript , as shown below:

Through prototype property of the constructor.

Through Object.getPrototypeOf(obj) method.

The difference between the two is that the prototype property of the constructor is generally only used in conjunction with the constructor, while the Object.getPrototypeOf(obj) method is generally a method for obtaining the prototype of the object instantiated by the constructor.

The example code is as follows:

// Constructor function Person(name) {
  this.name = name
}

// Pointing to the prototype of the constructor var p1 = Person.prototype

var person = new Person('Yiwan Zhou')

// Pointing to the prototype of the constructor var p2 = Object.getPrototypeOf(person)

console.log(p1 === p2) // true

After obtaining the prototype, you can operate it like an object, because the prototype itself is an object.

2. Prototype properties

In JavaScript , a function itself is also an object that contains methods and properties. Next, we will learn another property of the function object - prototype. The initial value of this property is an empty object.

2.1 Use prototypes to add properties and methods.

Another way to add properties and methods to an object is to add them through its prototype. When you add prototype properties and prototype methods to a constructor, all objects new created by the constructor share the properties and methods.

PS: The so-called prototype properties or prototype methods are properties or methods added through the prototype.

There are several ways to add properties and methods:

Directly add attributes or methods to it

Add properties or methods through Object.defineProperty() method. This method is safer than the first method.

Add objects directly to the prototype.

The sample code is as follows:

//Constructor function Fun() {}
//Add properties and methods directly to the constructor Fun.prototype.str = 'This is a string'
Fun.prototype.fn = function () {
  console.log('This is a method')
}
//Add properties or methods through defineProperty Object.defineProperty(Fun.prototype, 'MyFun', {
  value: function () {
    console.log('this is MyFun')
  },
})
//Test console.log(Fun.prototype.str)
Fun.prototype.fn()
Fun.prototype.MyFun()
var fun = new Fun()
fun.MyFun()
//Directly define an object to cover the previous prototype Fun.prototype = {
  name: 'A bowl of Zhou',
  fun: function () {
    console.log('this is function')
  },
}
Fun.prototype.fun()
var fun = new Fun()
fun.fun()

2.2 Accessing prototype properties and prototype methods

The most important thing about a prototype is its real-time nature. Since almost all objects in JavaScript are passed by reference, each new object entity we create does not have its own copy of the prototype. This means that we modify prototype property at any time, and the prototype property of all objects created by the same constructor will also change at the same time, including the properties and methods we created through the constructor.

Still using the above code, we add a new method to the prototype and call it. The sample code is as follows:

Fun.prototype.fn = function () {
  console.log('This is a method')
}
fun.fn() //This is a method

The objects we created earlier can access the newly added prototype properties and prototype methods.

3. Own properties and prototype properties

Let's first create a constructor and add two prototype properties to it.

//Constructor function Fun() {}
//Add prototype properties and methods Fun.prototype.name = 'a bowl of porridge'
Fun.prototype.print = function () {
  console.log('this is function')
}

Create an object through the constructor and set its properties and methods

//Create an object through the constructor var fun = new Fun()
//Add properties and methods to the object fun.name = 'Yiwan Zhou'
fun.SayMe = function () {
  console.log('this is SayMe')
}

Now our fun object has two own properties/methods and two prototype properties/methods. We access these properties and methods in turn.

//Access properties and methods console.log(fun.name) // Yiwan Zhou fun.SayMe() // this is SayMe
fun.print() // this is function


When we access the name property, the JavaScript engine will traverse all the properties of the fun object and return the value of the name property. The same is true for the SayMe() method. However, when it comes to the print() method, JavaScript engine will still traverse all the properties of the object. At this time, it will not find a print() method. Next, JavaScript engine will access the prototype of the constructor function that created the current object, that is, our Fun.prototype . If there is such a property, it will return immediately, otherwise it will return undefined or throw an exception.

Conclusion: When there are own properties, give priority to accessing the own properties, and then access the prototype properties.

3.1 Detecting own properties or prototype properties

Now we know the concepts and uses of owned properties and prototype properties, but how do we know whether a property is a free property or an original property? JavaScript provides the following two ways to detect the status of a property.

Use Object.prototype.hasOwnProperty(prop) method to detect whether the prop property is a free property. This method returns a Boolean value. If it is an owned property, it returns true, otherwise it returns false.

Use the in keyword to detect whether the object and prototype chain have the specified property.

The test code is as follows:

// Use the Object.prototype.hasOwnProperty(prop) method to check whether it is an owned property console.log(fun.hasOwnProperty('name')) // true
console.log(fun.hasOwnProperty('print')) // false
// If a non-existent attribute is detected, the result is also false
console.log(fun.hasOwnProperty('SayMe')) // true

// via the in operator console.log('name' in fun) // true
console.log('print' in fun) // true
console.log('SayMe' in fun) // true

Through testing, we found that these two methods cannot detect whether a property is an own property or a prototype property, but combining these two methods can detect whether it is an own property or a prototype property.

The sample code is as follows:

function DetectionAttributes(obj, attr) {
  if (attr in obj) {
    if (obj.hasOwnProperty(attr)) {
      // If it is an own attribute, return 1
      return 1
    } else {
      // If it is a prototype property, return 0
      return 0
    }
  } else {
    // If there is no such attribute, return -1
    return -1
  }
}


The test is as follows:

console.log(DetectionAttributes(fun, 'name')) // 1
console.log(DetectionAttributes(fun, 'print')) // 0
console.log(DetectionAttributes(fun, 'SayMe')) // 1

4. isPrototypeOf() method

isPrototypeOf() method is used to detect whether an object exists in the prototype chain of another object. If so, it returns true, otherwise it returns false.

The example code is as follows:

// Define an object to assign to the prototype object var obj = function () {
  this.name = 'A bowl of Zhou'
}
var Hero = function () {} // Define the constructor // Assign the defined object to the prototype of the constructor Hero.prototype = obj

// Create an object through Hero var hero1 = new Hero()
var hero2 = new Hero()
// Determine whether the two created objects are in the prototype chain of obj console.log(obj.isPrototypeOf(hero1)) // true
console.log(obj.isPrototypeOf(hero2)) // true

5. Extending built-in objects

Some of the built-in objects in JavaScript also have prototype properties. prototype property of the built-in objects can be used to extend the properties and methods of the built-in objects.

It is very flexible to extend the properties and methods of built-in objects through prototypes, and the specific content of the JavaScript language can be formulated according to personalized requirements.

There are two ways to extend built-in objects, as follows:

By directly adding new properties and methods.

Use the defineProperty() method of the Object object to add new properties or methods. This method is better than the first one because the created properties and methods are more secure.

The sample code is as follows:

// Extend properties and methods for Object // Use the first method Object.prototype.MyPrint = function () {
  console.log('this is MyPrint()')
}
// Using the second method Object.defineProperty(Object.prototype, 'MyInput', {
  value: function () {
    console.log('this is MyInput()')
  },
})
// Call Object.prototype.MyPrint() // this is MyPrint()
Object.prototype.MyInput() // this is MyInput()

6. Conclusion

This article introduces the concept of prototype in JavaScript, prototype properties, how to detect own properties and prototype properties, and how to extend built-in objects.

This is the end of this article about the details of JavaScript prototype. For more relevant JavaScript prototype content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Javascript Prototype
  • isPrototypeOf Function in JavaScript
  • A thorough understanding of js native syntax prototype, __proto__ and constructor
  • JavaScript uses the prototype property to implement inheritance operations example
  • Implementation of JS array dimensionality reduction Array.prototype.concat.apply([], arr)
  • Extension of js String.prototype.trim character to remove leading and trailing spaces
  • JavaScript __proto__ and prototype

<<:  Reference SVG images in CSS to support dynamic color switching implementation code

>>:  Master-slave synchronization configuration of Mysql database

Recommend

Example of using Docker to build an ELK log system

The following installations all use the ~/ direct...

How to detect Ubuntu version using command line

Method 1: Use the lsb_release utility The lsb_rel...

Two usages of iFrame tags in HTML

I have been working on a project recently - Budou...

WeChat applet realizes horizontal and vertical scrolling

This article example shares the specific code for...

How to change the terminal to a beautiful command line prompt in Ubuntu 18

I reinstalled VMware and Ubuntu, but the command ...

Full steps to create a password generator using Node.js

Table of contents 1. Preparation 2. Writing comma...

nginx+tomcat example of accessing the project through the domain name

I was curious about how to access the project usi...

Linux Check the installation location of the software simple method

1. Check the software installation path: There is...

Zabbix redis automatic port discovery script returns json format

When we perform automatic discovery, there is alw...

Differentiate between null value and empty character ('') in MySQL

In daily development, database addition, deletion...

Tips for Mixing OR and AND in SQL Statements

Today, there is such a requirement. If the logged...

VMware vSphere 6.7 (ESXI 6.7) graphic installation steps

Environment: VMware VCSA 6.7 (VMware-VCSA-all-6.7...