Table of Contents
Using
Source code analysis
Summary
Home Web Front-end JS Tutorial Detailed explanation of isPlainObject() instances in jQuery

Detailed explanation of isPlainObject() instances in jQuery

Feb 28, 2018 pm 02:20 PM
jquery Detailed explanation

The isPlainObject() function in jQuery is used to determine whether the specified parameter is a pure object, and the return value is of Boolean type.

"Pure objects" are objects created through { }, new Object(), Object.create(null).

The purpose of this method is to distinguish it from other JavaScript objects such as null, arrays, host objects (documents), DOM, etc., because using typeof on these will return object.

Using

Syntax:
$.isPlainObject(object)
Parameter description:
object: Any value of any type that needs to be judged.

$.isPlainObject({});    //true
$.isPlainObject(new Object);    //true
$.isPlainObject(Object.create(null));    //true
$.isPlainObject([]);    //false
$.isPlainObject(document);    //false
Copy after login

Source code analysis

Let’s take a look at the source code under jQuery 3.3.1 version

var class2type = {};

//Object.getPrototypeOf() 方法返回指定对象的原型(内部[[Prototype]]属性的值)。
var getProto = Object.getPrototypeOf;

//相当于  Object.prototype.toString
var toString = class2type.toString;

//hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性
//相当于 Object.prototype.hasOwnProperty
var hasOwn = class2type.hasOwnProperty;

//因为 hasOwn 是一个函数,所以这里调用的是内置对象 Function 的toString() 方法
//相当于  Function.prototype.toString
var fnToString = hasOwn.toString;

//相当于  Function.prototype.toString.call(Object)
//就是Object 构造函数 转字符串的结果
// ObjectFunctionString 其实就是 "function Object() { [native code] }" 这样的一个字符串
var ObjectFunctionString = fnToString.call(Object);

function isPlainObject (obj) {
  var proto, Ctor;

  //先去掉类型不是 Object 的
  //也就是用 Object.prototype.toString.call(obj) 这种方式,返回值不是 "[object Object]" 的,比如 数组 window history 
  if (!obj || toString.call(obj) !== "[object Object]") {
    return false;
  }

  //获取对象原型,赋值给 proto 
  proto = getProto(obj);

  //如果对象没有原型,那也算纯粹的对象,比如用 Object.create(null) 这种方式创建的对象 
  if (!proto) {
    return true;
  }

  //最后判断是不是通过 "{}" 或 "new Object" 方式创建的对象
  //如果 proto 有 constructor属性,Ctor 的值就为 proto.constructor,
  //原型的 constructor 属性指向关联的构造函数
  Ctor = hasOwn.call(proto, "constructor") && proto.constructor;

  //如果 Ctor 类型是  "function" ,并且调用Function.prototype.toString 方法后得到的字符串 与 "function Object() { [native code] }" 这样的字符串相等就返回true
  //用来区分 自定义构造函数和 Object 构造函数
  return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
}
Copy after login

Summary

From the source code, isPlainObject() method The implementation is mainly divided into three parts
1. Remove the type that is not Object.
Use the Object.prototype.toString.call() method. This method will get different strings for all types instead of using typeof , because typeof can only distinguish basic types, such as arrays, typeof still returns "object" string

var arr = [];
var obj = {};

typeof arr;        //"object"
typeof obj;        //"object"
typeof document;        //"object"

Object.prototype.toString.call(arr);        //"[object Array]"
Object.prototype.toString.call(obj);        //"[object Object]"
Object.prototype.toString.call(document);        //"[object HTMLDocument]"
Copy after login

2. Determine whether the object has a prototype. Objects without prototypes are considered pure objects

3 , Determine whether the object is created through "{}" or "new Object"
This requires judging their constructor, so use the Function.prototype.toString method

Function object covers the The Object.prototype.toString method inherited from Object.
The toString method of the function will return a string representing the function source code. Specifically, it includes the function keyword, formal parameter list, braces, and the content in the function body.
function fn(said){
    this.say = said;
}

Function.prototype.toString.call(fn); 
//"function fn(said){
//    this.say = said;
//}"

Function.prototype.toString.call(Object);
//"function Object() { [native code] }"
Copy after login

Related recommendations:

jQuery.isPlainObject() function usage details


The above is the detailed content of Detailed explanation of isPlainObject() instances in jQuery. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

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

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles