Home WeChat Applet Mini Program Development Detailed explanation of implicit calls in javascript

Detailed explanation of implicit calls in javascript

Mar 17, 2018 pm 03:46 PM
javascript js Detailed explanation

This time I will bring you a detailed explanation of the implicit call of javascript. What are the precautions for implicit call using javascript. The following is a practical case, let's take a look.

Preface

I don’t know if it is accurate to describe it as implicit calling. Its behavior is always hidden behind the scenes, and it shows its face from time to time. It doesn’t seem to have much effect, but it is still useful to understand it. Guaranteed to be of great use under your use.

The so-called implicit call simply means automatically calling some methods, and these methods can be modified externally like hooks, thereby changing the established behavior.
Below I will list some implicit calls that I have seen recently. The examples are just to the point. Welcome to add

DataType conversion toSting and valueOf

var obj = {
   a: 1,
   toString: function () {
    console.log('toString')
    return '2'
   },
   valueOf: function () {
    console.log('valueOf')
    return 3
   }
  }
  console.log(obj == '2'); //依次输出 'valueOf' false
  console.log(String(obj));//依次输出 'toString' '2'
Copy after login
var obj = {
   a: 1,
   toString: function () {
    console.log('toString')
    return '2'
   },
   valueOf: function () {
    console.log('valueOf')
    return {} //修改为对象
   }
  }
  console.log(obj == '2'); //依次输出 'valueOf' 'toString' true
  console.log(Number(obj));//依次输出 'valueOf' 'toString' 2
Copy after login

In the operation of the equality operator, the object will first call valueOf. If the returned value is an object, it will call toSting, except null, and then use the returned value for comparison. The first example is equivalent to 3 == '2' outputs false. In the second example, executing valueOf returns an object, and then executes toString. Finally, it is equivalent to '2' == '2' and outputs true. In the Number and String methods, Number will call valueOf first. , and then call toString, which is the opposite in the String method.

In addition to the above two examples, conversion of data types also exists in various other operations, such as numerical operations. When reference types are involved, the valueOf or toString method will be called. , as long as the object is an object, it will inherit these two methods. We can override these two methods to affect the behavior of data type conversion

handleEvent in DOM2 event

var eventObj = {
   a: 1,
   handleEvent: function (e) {
    console.log(this, e);//返回 eventObj 和 事件对象
    alert(this.a)
   }
  }
  document.addEventListener('click', eventObj)
Copy after login

You read that right, the second parameter of addEventListener can be an object in addition to a function. After the event is triggered, the handleEvent method of the object will be executed. When the method is executed, this points to eventObj. You can bind the data you want to pass in. Defined On the eventObj object

JSON object toJSON

var Obj = {
   a: 10,
   toJSON: function () {
    return {
     a: 1,
     b: function () {
     },
     c: NaN,
     d: -Infinity,
     e: Infinity,
     f: /\d/,
     g: new Error(),
     h: new Date(),
     i: undefined,
     
    }
   }
  }
  console.log(JSON.stringify(Obj));
  //{"a":1,"c":null,"d":null,"e":null,"f":{},"g":{},"h":"2018-02-09T19:29:13.828Z"}
Copy after login

If the object passed in by the stringify method of JSON has a toJSON method, then the object executed by this method will Convert to the object returned after toJSON is executed. One thing to note is that if the following code

var Obj1 = {
   a: 10,
   toJSON: function () {
    console.log(this === Obj1);//true
    return this
   }
  }
  console.log(JSON.stringify(Obj1));//{"a":10}
Copy after login
 var Obj2 = {
   a: 10,
   toJSON: function () {
    console.log(this === Obj2);//true
    return {
     a: this
    }
   }
  }
  console.log(JSON.stringify(Obj2));//报错 Maximum call stack size exceeded
Copy after login

according to the above statement, it is obvious that the error is what we expected, but when returning this directly, no error is reported at all, so why not You can make a bold guess that it internally compares the object returned by toJSON with the original object. If they are equal, the then

##promise object's then

var obj = {
   then: function (resolve, reject) {
    setTimeout(function () {
     resolve(1000);
    }, 1000)
   }
  }
  Promise.resolve(obj).then(function (data) {
   console.log(data);// 延迟1秒左右输出 1000
  })
Copy after login
is used directly when Promise When the .resolve method passes in an object, if a then method exists, the then method will be executed immediately, which is equivalent to putting the method into a new Promise. In addition to Promise.resolve having this behavior, Promise.all also has this behavior

 var timePromise = function (time) {
    return new Promise(function (resolve) {
     setTimeout(function () {
      resolve(time);
     }, time)
    })
   }
   var timePromise1 = timePromise(1000);
   var timePromise2 = timePromise(2000);
   var timePromise3 = timePromise(3000);
   Array.prototype.then = function (resolve) {
     setTimeout(function () {
      resolve(4000);
     }, 4000)
    }
   Promise.all([timePromise1, timePromise2, timePromise3]).then(function (time) {
    console.log(time);// 等待4秒左右输出 4000
   })
Copy after login

Object attribute accessor get and set

var obj = {
    _age: 100,
    get age() {
     return this._age < 18 ? this._age : 18;
    },
    set age(value) {
     this._age = value;
     console.log(`年龄设置为${value}岁`);
    }
   }
   obj.age = 1000; //年龄设置为1000岁
   obj.age = 200; //年龄设置为200岁
   console.log(obj.age);// 18
   obj.age = 2; ////年龄设置为2岁
   console.log(obj.age); // 2
Copy after login
You can see that no matter what age is set, my age is 18 years old or below. When performing attribute access, actually It is to call the get set function corresponding to the object attribute. In addition to the above writing method, there is also the following writing method

 var input = document.createElement('input');
  var span = document.createElement('span');
  document.body.appendChild(input);
  document.body.appendChild(span);
  var obj = {
   _age:''
  }
  var obj = Object.defineProperty(obj, 'age', {
   get: function () {
    return this._age;
   },
   set: function (value) {
    this._age = value;
    input.value = value;
    span.innerHTML = value;
   }
  });
  input.onkeyup = function (e) {
   if (e.keyCode === 37 || e.keyCode === 39) {
    return;
   }
   obj.age = this.value
  }
Copy after login
Now the value value of input and the innerHTML value of obj.age attribute value span are bound together

Iterator interface Symbol.iterator

 var arr = [ 1, 2 , 3];
  arr[Symbol.iterator] = function () {
   const self = this;
   let index = 0;
   return {
    next () {
     if(index < self.length) {
      return {
       value: self[index] ** self[index++],
       done: false
      }
     } else {
      return {
       value: undefined,
       done: true
      }
     }
    }
   }
  }
  console.log([...arr, 4]);//返回 [1, 4, 27, 4]
  for(let value of arr) {
   console.log(value); //依次返回 1 4 27
  }
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

JS Add Element New Node

4 Ways to JS Loop Nodelist Dom List

How to achieve the intermittent loop scrolling effect of JS text

The above is the detailed content of Detailed explanation of implicit calls in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles