Home Web Front-end JS Tutorial Basic concept of prototype of Object object in JS

Basic concept of prototype of Object object in JS

Jan 31, 2018 am 09:28 AM
javascript object basic concept

This article is about the basic content of JS learning and learning the prototype concept of Object object. Friends who are interested can refer to it. Hope it helps everyone.

Object concept

In JavaScript, all reference types are objects. For example, in function Foo () {}, Foo itself is a reference to an object.

Create object method literal method new constructor function declaration Object.create

Literal object

Javascript language level quick creation of instances of objects


var obj = {foo: 'foo', bar: 'bar'}; // Object对象字面量
var obj2 = [obj, 'foo', 'bar']; // Array数组字面量
var obj3 = /^[a-zA-Z0-9]$/; // RegExp正则字面量
var obj4 = function(){}; // Function函数字面量
Copy after login

new Constructor

Through the constructor of the built-in object, or a custom function. Use the new operator to create an object and execute the constructor method.


var obj = new Object();
var obj2 = new Array(1000);
var obj3 = new RegExp('^[a-zA-Z0-9]$');
var obj4 = new Function('a', 'b', 'return a + b;');
Copy after login

Function declaration

The object created by the function declaration. Functions are special objects.


function Foo() {}
Foo instanceof Object;
Foo instanceof Function;
Copy after login

Object.create

Pass in an object as the prototype of the returned object, create a new object, and point the prototype of the new object to the passed in object .


var foo = {
 'foo': 'foo',
 'bar': 'bar'
};
var o = Object.create(foo); // o.__proto__ = foo
console.log(o.foo); // o.__proto__.foo
Copy after login

Use Object.create(null) to return a dictionary object.


var o = Object.create(null);
o instanceof Object; // return false;
o.toString(); // Uncaught TypeError
Copy after login

Object prototype

Every object has a built-in __proto__ attribute pointing to the function that constructed it prototype attribute. And the constructor's

prototype.constructor points to the constructor itself. The process of searching for an object's attributes consists of the following parts:

Search for the data descriptor (writable, value) or access descriptor (getter, setter) of the object's attributes. If found, return the corresponding value. If the query cannot be found, proceed to step 2. Find whether the value of the object property is explicitly defined (can be detected by Object.getOwnPropertyNames). If the object property is defined, the defined value is returned. If not, proceed to step 3. Find the hidden prototype of the object__proto__The properties of the object, the rules are the same as steps 1 and 2. If it has not been found, repeat step 3 until __proto__ is null.

The specific case is shown in the figure below:

#Detecting object prototype

Test an object in its prototype chain Whether there is a prototype attribute of a constructor in

instanceof Object.prototype.isPrototypeOf

instanceof

operator, language-level detection of the prototype of the object Whether the chain contains the prototype of the constructor


function Foo () {}
Foo instanceof Function; // return true
Foo instanceof Object; // return true
Copy after login

SimulationinstanceofFind whether the constructor of the object's prototype chain contains the incoming constructor, __proto__ In some specific browsers, there is a prototype object exposed to the user


function Bar () {}
function isInstanceof (obj, Constructor) {
 if (obj === null) {
 return false;
 }
 // 忽略 string, number, boolean, null, undefined 类型干扰
 if (!~['object', 'function'].indexOf(typeof obj)) {
 return false;
 }

 var prototype = obj.__proto__;
 while(prototype) {
 if (prototype.constructor === Constructor) {
  return true;
 }
 prototype = prototype.__proto__;
 }
 return false;
}
isInstanceof(Bar, Function);
isInstanceof(Bar, Object);
Copy after login

isPrototypeOf

The prototype object of the constructor comes with The function attribute is used to detect whether the prototype object of the constructor exists in the prototype chain of the target object.


function Baz () {}
var baz = new Baz();
Baz.prototype.isPrototypeOf(baz);
Function.prototype.isPrototypeOf(baz);
Object.prototype.isPrototypeOf(baz);
Copy after login

Get the object prototype Object.getPrototypeOf __proto__


##

var o = {};
var prototype = Object.getPrototypeOf(o);
console.log(prototype === Object.prototype); // return true
// 部分浏览器有效
var o2 = {};
console.log(o2.__proto__ === Object.prototype); // return true
Copy after login

Set the object prototype Object. create Object.setPrototypeOf

Object.create

Return an object and set its prototype


function Foo () {}
 function Bar () {}
 Foo.prototype.foo = 'foo';
 Bar.prototype = Object.create(Foo.prototype); 
 Bar.prototype.constructor = Bar; // 修正原型链的constructor
 var o = new Bar();
 console.log(o.foo); // return foo;
 console.log(o instanceof Bar); // return true
Copy after login

Object.setPrototypeOf

Set the implicit prototype of the object directly

__proto__


function Foo () {}
 Foo.prototype.name = 'foo';
 var o = Object.create(null);
 Object.setPrototypeOf(o, Foo.prototype);
 console.log(o.name); // return foo
Copy after login

Related recommendations :

Summary of things to note about the Object object

Sample code explaining the Object object in JavaScript

jQuery serializes the form into an instance of the Object object


The above is the detailed content of Basic concept of prototype of Object object in JS. 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Getting started with Java crawlers: Understand its basic concepts and application methods Getting started with Java crawlers: Understand its basic concepts and application methods Jan 10, 2024 pm 07:42 PM

A preliminary study on Java crawlers: To understand its basic concepts and uses, specific code examples are required. With the rapid development of the Internet, obtaining and processing large amounts of data has become an indispensable task for enterprises and individuals. As an automated data acquisition method, crawler (WebScraping) can not only quickly collect data on the Internet, but also analyze and process large amounts of data. Crawlers have become a very important tool in many data mining and information retrieval projects. This article will introduce the basic overview of Java crawlers

See all articles