This article gives you a detailed introduction to the knowledge points related to implicit calls in JavaScript. Those who are interested in this can learn together.
Preface
I don’t know if it is accurate to use implicit calling to describe it. 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 useful 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
Data type 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'
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
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. The second example returns an object because valueOf is executed, and then toString is executed. Finally, it is equivalent to '2' == '2' and outputs true. In the Number and String methods, Number will call valueOf first, and then toString. String The method is the opposite.
In addition to the two examples above, data type conversion also exists in various other operations, such as numerical operations. When reference types are involved, the valueOf or toString method will be called, and as long as it is an object, it will be inherited. We can re-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)
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 to 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"}
If the object passed in by the stringify method of JSON has a toJSON method, then the object executed by the method will be converted to the object returned after toJSON is executed. There is one thing to note. Note 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}
var Obj2 = { a: 10, toJSON: function () { console.log(this === Obj2);//true return { a: this } } } console.log(JSON.stringify(Obj2));//报错 Maximum call stack size exceeded
is based on the above statement, it is obvious that the error is what we expected, but when directly returning this, no error is reported at all. You might as well make a bold guess about the internal objects returned by toJSON and Compare the original objects, and if they are equal, use the then of the original object
promise object
var obj = { then: function (resolve, reject) { setTimeout(function () { resolve(1000); }, 1000) } } Promise.resolve(obj).then(function (data) { console.log(data);// 延迟1秒左右输出 1000 })
When the Promise.resolve method passes in the object, if there is a then method 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 })
Object attribute accessors 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
You can see that no matter how much the age is set, my age is 18 years old or below. When performing attribute access, the corresponding get set function of the object attribute is actually called. In addition to the above The writing method is also as follows
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 }
Now the 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 }
You can see that whenever you call the spread operator, or use for...of to loop through an object, you will call the object's traverser interface, such as Array, String, Map, Set, TypedArray and others. Array-like objects such as arguments and NodeList natively have a traverser interface, but ordinary objects do not deploy this interface. If you want the object to be able to use the spread operator or for...of loop, you can add this method to the object, or you can add it to the original object. Overriding methods on objects with interfaces to change their behavior
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
What security vulnerabilities exist when using timing-attack in node applications
Implementing one-way in the vue component delivery object Binding, how to do it?
How to use TypeScript methods in Vue components (detailed tutorial)
The above is the detailed content of How to use implicit calls in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
