Home Web Front-end JS Tutorial Beyond Jquery_01_isPlainObject analysis and reconstruction_javascript skills

Beyond Jquery_01_isPlainObject analysis and reconstruction_javascript skills

May 16, 2016 pm 06:18 PM
analyze Refactor

isPlainObject is a new method provided after Jquery 1.4, used to determine whether the object is a pure object (created through "{}" or "new Object").

Use isPlainObject
First, let’s understand what a ‘pure object’ is. A simple understanding of ‘pure object’ refers to an object constructed from Object. So which objects are constructed from Object. The first thing to bear the burden must be the object constructed by new Object(). Note: nothing is added in the brackets after Object. Because Object is the foundation of all 'classes', it has some special behaviors. For example, when new Object(3) is called, a Number type object will be constructed. new Object('') will construct an object of type String. Then objects defined in the form {} also belong to 'pure objects'. The essence of '{}' is new Object(), but its expression is different. Okay, let’s look at a piece of code:

Copy the code The code is as follows:

var objStr = new Object('');
alert(objStr.constructor);//String
alert(isPlainObject(objStr));//false
var objNum = new Object(3);
alert (objNum.constructor);//Number
alert(isPlainObject(objNum));//false
function Person(){}
var person = new Person();
alert(isPlainObject( person));//false
var obj01 = new Object();
obj01.name = 'Idiot's motto';
alert(isPlainObject(obj01));//true
alert( isPlainObject({name:'Motto of Idiot'}));//true

isPlainObject source code analysis
The following code is the complete version of isPlainObject in Jquery. The comments are very detailed. I Not much more to say.
Copy code The code is as follows:

var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty;
function isPlainObject( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
//Make sure that DOM nodes and window objects don't pass through, as well
//windows objects:toString.call(window):IE [object Object] FF [object Window] chrome [window global] safari [object DOMWindow]
//DOM nodes:toString.call(#div01):IE [object Object] FF [object Window] chrome [object global] safari [object DOMWindow]
//Conclusion: obj.nodeType || obj.setInterval is mainly used to judge IE browsers
//Note: setInterval of history, location, navigator, and screen is undefined
if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
return false;
}
// Not own constructor property must be Object
// Remove custom objects and Judgment of built-in objects, such as function Person(){} var p = new Person();String,Number
if ( obj.constructor //There is constructor property
&& !hasOwnProperty.call(obj, "constructor" ) //And the constructor property must be defined in the prototype chain
&& !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")//And there is an isPrototypeOf method in the prototype, generally only in the prototype of Object Only this method
) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
//For complex class structures, if there is inheritance...
/*
//A simple test
function Animal(name){
}
function Person(name,age){
Animal.call(this,name);
this.age =age;
}
var p = new Person('jxl',20);
for(key in p){
alert(hasOwnProperty.call( p, key ))//true , false
}
*/
var key;
for ( key in obj ) {}
return key === undefined || hasOwnProperty.call( obj, key );
}

Ask a question
Personally, I feel that this implementation is more complicated, and there are BUG.
Simple BUG, ​​history, location, navigator, screen can sequentially return true through the detection of isPlainObject.
Let’s take a look at my solution (modify BUG, ​​simplify):
Copy code The code is as follows:

function isPlainObject(obj){
if(obj&&Object.prototype.toString.call(obj)= ==="[object Object]"&&obj.constructor===Object &&!hasOwnProperty.call(obj, "constructor")){
var key;
for ( key in obj ) {}
return key === undefined || hasOwnProperty.call( obj, key );
}
return false;
}

There is also a BUG, ​​and it is an unsolvable BUG :
Copy code The code is as follows:

function m(){};
m.prototype.constructor=Object; //Must kill
obj=new m;
alert(isPlainObject(obj)); //true

Another one with the same logic:
Copy the code The code is as follows:

function m(){};
m.prototype = {};
obj=new m;
alert(isPlainObject(obj)); //true

This answer is unsolvable!

The answer is unsolvable
I thought this problem was easy to solve, but after digging deeper, I found that it was an unsolvable problem. The reason is as follows:
Copy code The code is as follows:

function Person(){};
Person.prototype.constructor=Object;
var person=new Person;

Let’s take a look at the current state of person:
Beyond Jquery_01_isPlainObject analysis and reconstruction_javascript skills
person and its construction The only connection to the function Person is the constructor attribute in its prototype chain. When we judge whether it is a 'pure object', it is mainly based on the constructor of the object instance. If we point it to Object, as you can see in the picture, then person and Person have no relationship in code. It is precisely because of this that problems arise in type judgment.
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)

How to implement data statistics and analysis in uniapp How to implement data statistics and analysis in uniapp Oct 24, 2023 pm 12:37 PM

How to implement data statistics and analysis in uniapp 1. Background introduction Data statistics and analysis are a very important part of the mobile application development process. Through statistics and analysis of user behavior, developers can have an in-depth understanding of user preferences and usage habits. Thereby optimizing product design and user experience. This article will introduce how to implement data statistics and analysis functions in uniapp, and provide some specific code examples. 2. Choose appropriate data statistics and analysis tools. The first step to implement data statistics and analysis in uniapp is to choose the appropriate data statistics and analysis tools.

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Case analysis of Python application in intelligent transportation systems Case analysis of Python application in intelligent transportation systems Sep 08, 2023 am 08:13 AM

Summary of case analysis of Python application in intelligent transportation systems: With the rapid development of intelligent transportation systems, Python, as a multifunctional, easy-to-learn and use programming language, is widely used in the development and application of intelligent transportation systems. This article demonstrates the advantages and application potential of Python in the field of intelligent transportation by analyzing application cases of Python in intelligent transportation systems and giving relevant code examples. Introduction Intelligent transportation system refers to the use of modern communication, information, sensing and other technical means to communicate through

In-depth understanding of function refactoring techniques in Go language In-depth understanding of function refactoring techniques in Go language Mar 28, 2024 pm 03:05 PM

In Go language program development, function reconstruction skills are a very important part. By optimizing and refactoring functions, you can not only improve code quality and maintainability, but also improve program performance and readability. This article will delve into the function reconstruction techniques in the Go language, combined with specific code examples, to help readers better understand and apply these techniques. 1. Code example 1: Extract duplicate code fragments. In actual development, we often encounter reused code fragments. At this time, we can consider extracting the repeated code as an independent function to

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Analyze the advantages and disadvantages of static positioning technology Analyze the advantages and disadvantages of static positioning technology Jan 18, 2024 am 11:16 AM

Analysis of the advantages and limitations of static positioning technology With the development of modern technology, positioning technology has become an indispensable part of our lives. As one of them, static positioning technology has its unique advantages and limitations. This article will conduct an in-depth analysis of static positioning technology to better understand its current application status and future development trends. First, let’s take a look at the advantages of static positioning technology. Static positioning technology achieves the determination of position information by observing, measuring and calculating the object to be positioned. Compared with other positioning technologies,

ThinkPHP6 code performance analysis: locating performance bottlenecks ThinkPHP6 code performance analysis: locating performance bottlenecks Aug 27, 2023 pm 01:36 PM

ThinkPHP6 code performance analysis: locating performance bottlenecks Introduction: With the rapid development of the Internet, more efficient code performance analysis has become increasingly important for developers. This article will introduce how to use ThinkPHP6 to perform code performance analysis in order to locate and solve performance bottlenecks. At the same time, we will also use code examples to help readers understand better. Importance of Performance Analysis Code performance analysis is an integral part of the development process. By analyzing the performance of the code, we can understand where a lot of resources are consumed

Analyze and solve the reasons why Tomcat crashes Analyze and solve the reasons why Tomcat crashes Jan 13, 2024 am 10:36 AM

Tomcat crash cause analysis and solutions Introduction: With the rapid development of the Internet, more and more applications are developed and deployed on servers to provide services. As a common JavaWeb server, Tomcat has been widely used in application development. However, sometimes we may encounter problems with Tomcat crashing, which will cause the application to not run properly. This article will introduce the analysis of the causes of Tomcat crash, provide solutions, and give specific code examples.

See all articles