This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

An overview of the

What is the prototype

In JavaScript, a Function is an object of type Function that contains properties and methods. A Prototype is an attribute of a Function object.

The prototype attribute is included in the function definition, and its initial value is an empty object. There is no primitive type of function defined in JavaScript, so the prototype can be any type.

Stereotypes are used to hold the shared properties and methods of an object. The properties and methods of a stereotype do not affect the properties and methods of the function itself.

The sample code is validated below

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

Copy the code

Prototype returns an empty Object, but that doesn’t mean there are no properties or methods in Object.prototype. These properties and methods are not enumerable.

function fun() {
  console.log('Function prototype')}console.log(fun.prototype) / / {}
/ / by the Object. GetOwnPropertyNames () for all attributes
console.log(Object.getOwnPropertyNames(fun.prototype)) // [ 'constructor' ]

Copy the code

Where the constructor property points to a reference to the constructor as follows:

/ / the constructor property

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

console.log(fun.prototype.constructor === fun) // true
Copy the code

To get the prototype

After understanding the concept and function of a prototype, we need to obtain a prototype before we can operate on it. There are two ways to obtain a prototype in JavaScript, as follows:

  1. Through the constructor’s Prototype property.

  2. The Object. GetPrototypeOf (obj) method.

The difference is that the constructor’s prototype property is usually used only with the constructor, while object.getProtoTypeof (obj) is usually used to get the instantiated Object of the constructor.

Example code is as follows:

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

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

var person = new Person('Bowl Week')

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

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

Copy the code

Once you get a prototype, you can manipulate it as if it were an object, because the prototype is an object.

The prototype property

In JavaScript, a function is itself an object that contains methods and properties. You’ll learn about another function object property, prototype, whose initial value is an empty object.

Add properties and methods using stereotypes.

Another way to add properties and methods to an object is through a stereotype. When you add stereotype properties and methods to a constructor, all objects new from the constructor share the properties and methods.

PS: A stereotype attribute or method is a property or method added through a stereotype.

You can add attributes and methods in the following ways

  1. Add attributes or methods directly to it

  2. Add attributes or methods using the object.defineProperty () method. This method is more secure than the first method.

  3. Add objects directly to the stereotype.

The sample code looks like this:

// constructor
function Fun() {}
// Add attributes and methods directly to the constructor
Fun.prototype.str = 'This is a string.'
Fun.prototype.fn = function () {
  console.log('That's one way.')}// Add attributes or methods via 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()
// Define an object directly to override the previous prototype
Fun.prototype = {
  name: 'Bowl Week'.fun: function () {
    console.log('this is function')
  },
}
Fun.prototype.fun()
var fun = new Fun()
fun.fun()

Copy the code

Access the stereotype property stereotype method

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

Add a new method to the prototype and call it. The sample code looks like this:

Fun.prototype.fn = function () {
  console.log('That's one way.')
}
fun.fn() // This is one way

Copy the code

The objects we created earlier have access to the new stereotype properties and methods.

Own attributes and stereotype attributes

Let’s start by creating a constructor and adding two stereotype properties to it.

// constructor
function Fun() {}
// Add stereotype properties and methods
Fun.prototype.name = 'A bowl of porridge'
Fun.prototype.print = function () {
  console.log('this is function')}Copy the code

The constructor creates an object and sets its properties and methods

// Create an object using the constructor
var fun = new Fun()
// Add attributes and methods to the object
fun.name = 'Bowl Week'
fun.SayMe = function () {
  console.log('this is SayMe')}Copy the code

Now our Fun object has two properties/methods and two prototype properties/methods. Let’s access these properties and methods in turn.

// Access properties and methods
console.log(fun.name) / / a bowl of weeks
fun.SayMe() // this is SayMe
fun.print() // this is function
Copy the code

When we access the name property, the JavaScript engine iterates through all the properties of the fun object and returns the value of the Name property. The SayMe() method works the same way. But when we get to print(), the JavaScript engine will still iterate through all the properties of the object, and we won’t find a method called print(). The JavaScript engine will then access the prototype of the constructor function that created the current object, our fun.prototype, If it is present, return immediately; otherwise return undefined or throw an exception

Conclusion: When there are own attributes, access the own attributes first, after accessing the own attributes to access the prototype attributes.

Detect proprietary or stereotype properties

Now that we know the concepts and uses of proprietary and stereotype properties, how do we know if a property is a free property or an original property? JavaScript provides two ways to detect the condition of a property

  • Use Object. The prototype. HasOwnProperty (prop) method to test whether prop attribute is free attribute, this method returns a Boolean value, if it is their own property returns true, otherwise it returns false.

  • To use the IN keyword to detect whether an object and the stereotype chain have specified properties.

The test code is as follows:

/ / by the Object. The prototype. HasOwnProperty (prop) method to detect whether for their own properties
console.log(fun.hasOwnProperty('name')) // true
console.log(fun.hasOwnProperty('print')) // false
// If an attribute does not exist, the result is false
console.log(fun.hasOwnProperty('SayMe')) // true

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

Copy the code

Through testing, we found that the two methods can not detect whether a property is a own property or a stereotype property, but the two methods can be combined to detect whether it is a own property or a stereotype property, the example code is as follows:

function DetectionAttributes(obj, attr) {
  if (attr in obj) {
    if (obj.hasOwnProperty(attr)) {
      Property returns 1 if it is its own property
      return 1
    } else {
      // Returns 0 if it is a stereotype attribute
      return 0}}else {
    // Returns -1 without this attribute
    return -1}}Copy the code

The tests are as follows:

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

Copy the code

IsPrototypeOf () method

The isPrototypeOf() method checks if an object exists in another object’s prototype chain, returning true if it does, and false otherwise.

The example code is as follows:

// Define an object that can be assigned to the prototype object
var obj = function () {
  this.name = 'Bowl Week'
}
var Hero = function () {} // Define the constructor
// Assign the defined object to the constructor's prototype
Hero.prototype = obj

// Create an object with Hero
var hero1 = new Hero()
var hero2 = new Hero()
// Determine if the two objects created are in obj's prototype chain
console.log(obj.isPrototypeOf(hero1)) // true
console.log(obj.isPrototypeOf(hero2)) // true

Copy the code

Extended built-in objects

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

Extending the properties and methods of built-in objects through prototypes is very flexible, and the specific content of the JavaScript language can be customized according to individual requirements.

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

  • By adding properties and methods directly.

  • Add attributes or methods to an Object via its defineProperty() method. This approach is better than the first approach in that the properties and methods created are more secure

The sample code looks like this:

// Extend properties and methods for Object
// Use the first method
Object.prototype.MyPrint = function () {
  console.log('this is MyPrint()')}// Use 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()

Copy the code

Write in the last

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

This is the fifty-first article in the Learning front End series, The Prototype. If you like this column, please give me or the column a look

This series of articles in the nuggets first, preparation is not easy to reprint please obtain permission

Phase to recommend

  • Summary of 42 front-end layout schemes – Juejin (juejin. Cn)
  • – Juejin (juejin. Cn)