The most detailed explanation of JS prototype and prototype chain
1. Ordinary objects and function objects
In JavaScript, everything is an object! But the objects are also different. Divided into ordinary objects and function objects, Object and Function are the function objects that come with JS. The following is an example
var o1 = {};
var o2 =new Object(); var o3 = new f1();
function f1(){};
var f2 = function(){}; var f3 = new Function('str','console.log(str)');
console.log(typeof Object); //function
console.log(typeof Function); //function
console.log(typeof f1); //function
console.log(typeof f2); //function
console.log(typeof f3); //function
console.log(typeof o1); //object
console.log(typeof o2); //object
console.log(typeof o3); //object
In the above example, o1 o2 o3 is an ordinary object, and f1 f2 f3 is a function object. How to distinguish is actually very simple. All objects created through new Function() are function objects, and others are ordinary objects. f1, f2, are all created through new Function() in the final analysis. Function Objects are also created through New Function().
Be sure to distinguish between ordinary objects and function objects. We will use it frequently below.
2. Constructor
Let’s review the knowledge of constructor first:
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() { alert(this.name) }
}
var person1 = new Person('Zaxlct', 28, 'Software Engineer');
var person2 = new Person('Mick', 23, 'Doctor');
The above example Person1 and person2 are both instances of Person. Both instances have a constructor (constructor) attribute, which (is a pointer) points to Person. That is:
console.log(person1.constructor == Person); //true console.log(person2.constructor == Person); //true
We need to remember two concepts (constructor, instance): person1 and person2 are both instances of the constructor Person A formula: The constructor attribute (constructor) of the instance points to the constructor.
3. Prototype object
In JavaScript, whenever an object (function is also an object) is defined, the object will Contains some predefined properties. Each function object has a prototype attribute, which points to the prototype object of the function. (No matter what is used first, __proto__ will be analyzed in detail in the second lesson)
function Person() {}
Person.prototype.name = 'Zaxlct';
Person.prototype.age = 28;
Person.prototype.job = 'Software Engineer';
Person.prototype.sayName = function() {
alert(this.name);
}
var person1 = new Person();
person1.sayName(); // 'Zaxlct'
var person2 = new Person();
person2.sayName(); // 'Zaxlct'
console.log(person1.sayName == person2.sayName); //true
We got the first "law## in this article #》:
每个对象都有 __proto__ 属性,但只有函数对象才有 prototype 属性
So what is prototype object? If we change the above example, you will understand:
Person.prototype = {
name: 'Zaxlct',
age: 28,
job: 'Software Engineer',
sayName: function() {
alert(this.name);
}
}
The prototype object, as the name suggests, is an ordinary object (nonsense = =!). From now on you have to remember that the prototype object is Person.prototype. If you are still afraid of it, think of it as the letter A: var A = Person.prototype
Above we added four attributes to A: name, age, job, sayName. In fact, it also has a default attribute: constructor
##The above sentence is a bit confusing, let’s “translate” it: A has a defaultBy default, all prototype objects will Automatically obtain a constructor
(constructor) attribute, which (is a pointer) points to the function where the prototypeattribute is located (Person)
constructor Attribute, this attribute is a pointer pointing to Person. That is: Person.prototype.constructor == Person
In the second section "Constructor" above, we know the construction of the
instance The function attribute (constructor) points to the constructor : person1.constructor == Person
person1.constructor == Person
Person.prototype.constructor == Person
Why does Person.prototype have a constructor attribute? ? Likewise, Person.prototype (think of it as A) is also an instance of Person. That is, when Person is created, an instance object is created and assigned to its prototype. The basic process is as follows: 结论:原型对象(Person.prototype)是 构造函数(Person)的一个实例。 原型对象其实就是普通对象(但 Function.prototype 除外,它是函数对象,但它很特殊,他没有prototype属性(前面说道函数对象都有prototype属性))。看下面的例子: 那原型对象是用来做什么的呢?主要作用是用于继承。举个例子: 从这个例子可以看出,通过给 小问题,上面两个 this 都指向谁? 故两次 this 在函数执行时都指向 person1。 推荐教程:《JS教程》var A = new Person();
Person.prototype = A; // 注:上面两行代码只是帮助理解,并不能正常运行
function Person(){};
console.log(Person.prototype) //Person{}
console.log(typeof Person.prototype) //Object
console.log(typeof Function.prototype) // Function,这个特殊
console.log(typeof Object.prototype) // Object
console.log(typeof Function.prototype.prototype) //undefined
Function.prototype 为什么是函数对象呢? var A = new Function ();
Function.prototype = A;
上文提到凡是通过 new Function( ) 产生的对象都是函数对象。因为 A 是函数对象,所以
Function.prototype 是函数对象。var Person = function(name){
this.name = name; // tip: 当函数执行时这个 this 指的是谁?
};
Person.prototype.getName = function(){
return this.name; // tip: 当函数执行时这个 this 指的是谁?
}
var person1 = new person('Mick');
person1.getName(); //Mick
Person.prototype 设置了一个函数对象的属性,那有 Person 的实例(person1)出来的普通对象就继承了这个属性。具体是怎么实现的继承,就要讲到下面的原型链了。 var person1 = new person('Mick');
person1.name = 'Mick'; // 此时 person1 已经有 name 这个属性了
person1.getName(); //Mick
The above is the detailed content of The most detailed explanation of JS prototype and prototype chain. For more information, please follow other related articles on the PHP Chinese website!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe 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.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment







