I believe that many friends who have used JavaScript must have some understanding of prototype, but what exactly is prototype makes beginners at a loss. They only know that functions have a prototype attribute, and functions can be added to them. For example access, I don’t know about the others. Today I will introduce you to the detailed use of prototype in JavaScript!
Students who have used JavaScript must be familiar with prototype, but beginners are confused about what it is. They only know that functions have a prototype attribute, and functions can be added for instance access. Others I'm not sure. I recently read some advanced JavaScript programming and finally unveiled its mystery.
Each function has a prototype attribute, which is a reference to an object. This object is called a prototype object. The prototype object contains methods and properties shared by function instances, which means that the function is used as Constructor When called (using the new operator), the newly created object will inherit properties and methods from the prototype object.
Private variables and functions
Let’s talk about a few related things before talking about prototype in detail, so that we can better understand the design intention of prototype. A JavaScript Namespace article I wrote before mentioned JavaScript's Function Scope. If the variables and functions defined within the function do not provide an interface to the outside world, they will not be accessible from the outside. To, that is, become private variables and private functions.
The code is as follows:
function Obj(){ var a=0; //私有变量 var fn=function(){ //私有函数 } }
In this way, the variable a and function fn cannot be accessed outside the function object Obj, they become private and can only be used inside Obj, even if it is an instance of the function Obj Still unable to access these variables and functions
The code is as follows:
var o=new Obj(); console.log(o.a); //undefined console.log(o.fn); //undefined
Static variables, functions
Whendefine a functionThe attributes and functions added by "." can still be accessed through the object itself, but its instances cannot be accessed. Such variables and functions are called static variables and static functions respectively. Used in Java, C# students understand the meaning of static very well.
The code is as follows:
function Obj(){ } Obj.a=0; //静态变量 Obj.fn=function(){ //静态函数 } console.log(Obj.a); //0 console.log(typeof Obj.fn); //function var o=new Obj(); console.log(o.a); //undefined console.log(typeof o.fn); //undefined
Instance variables and functions
In addition to some library functions in Object-oriented programming We still hope to define some properties and methods at the same time when the object is defined, which can be accessed after instantiation. JavaScript can also do this
The code is as follows:
function Obj(){ this.a=[]; //实例变量 this.fn=function(){ //实例方法 } } console.log(typeof Obj.a); //undefined console.log(typeof Obj.fn); //undefined var o=new Obj(); console.log(typeof o.a); //object console.log(typeof o.fn); //function
This can achieve the above purpose, however
The code is as follows:
function Obj(){ this.a=[]; //实例变量 this.fn=function(){ //实例方法 } } var o1=new Obj(); o1.a.push(1); o1.fn={}; console.log(o1.a); //[1] console.log(typeof o1.fn); //object var o2=new Obj(); console.log(o2.a); //[] console.log(typeof o2.fn); //function
The running result of the above code is completely in line with expectations, but it also illustrates a problem. a and fn are modified in o1, but there is no change in o2. Due to the array and functions are both objects and reference types. This means that although the properties and methods in o1 and the properties and methods in o2 have the same name, they are not a reference, but a copy of the properties and methods defined by the Obj object.
This is not a problem for attributes, but it is a big problem for methods, because the methods are doing exactly the same function, but they are copied twice. If a function object has If there are thousands of instance methods, then each instance of it must maintain a copy of thousands of methods. This is obviously unscientific. What can we do? Prototype came into being.
prototype
Whenever a new function is created, a prototype attribute is created for the function according to a specific set of rules. By default, prototype The attribute will get a constructor attribute by default. This attribute is a pointer to the function where the prototype attribute is located. It's a bit confusing. Write the code and see the picture above!
The code is as follows:
function Person(){ }
As can be seen from the above figure, the Person object will automatically obtain the prototype attribute, and prototype is also an object and will automatically Get a constructor property, which points to the Person object.
When a constructor is called to create an instance, the instance will contain an internal pointer (the name of this pointer is proto in many browsers) pointing to the prototype of the constructor. This connection exists between the prototype of the instance and the constructor. between the instance and the constructor.
The code is as follows:
function Person(name){ this.name=name; } Person.prototype.printName=function(){ alert(this.name); } var person1=new Person('Byron'); var person2=new Person('Frank');
The instance person1 of Person contains the name attribute, and a proto attribute is automatically generated, which points to the prototype of Person. You can Accessing the printName method defined in the prototype probably looks like this
写段程序测试一下看看prototype内属性、方法是能够共享
代码如下:
function Person(name){ this.name=name; } Person.prototype.share=[]; Person.prototype.printName=function(){ alert(this.name); } var person1=new Person('Byron'); var person2=new Person('Frank'); person1.share.push(1); person2.share.push(2); console.log(person2.share); //[1,2]
果不其然!实际上当代码读取某个对象的某个属性的时候,都会执行一遍搜索,目标是具有给定名字的属性,搜索首先从对象实例开始,如果在实例中找到该属性则返回,如果没有则查找prototype,如果还是没有找到则继续递归prototype的prototype对象,直到找到为止,如果递归到object仍然没有则返回错误。同样道理如果在实例中定义如prototype同名的属性或函数,则会覆盖prototype的属性或函数。
代码如下:
function Person(name){ this.name=name; } Person.prototype.share=[]; var person=new Person('Byron'); person.share=0; console.log(person.share); //0而不是prototype中的[]
构造简单对象
当然prototype不是专门为解决上面问题而定义的,但是却解决了上面问题。了解了这些知识就可以构建一个科学些的、复用率高的对象,如果希望实例对象的属性或函数则定义到prototype中,如果希望每个实例单独拥有的属性或方法则定义到this中,可以通过构造函数传递实例化参数。
代码如下:
function Person(name){ this.name=name; } Person.prototype.share=[]; Person.prototype.printName=function(){ alert(this.name); }
总结:
相信通过对本文的详细学习,很多小伙伴都知道JavaScript中prototype的使用有了进一步的了解,希望对你的工作有所帮助!
相关推荐:
JavaScript向对象添加属性和方法的属性prototype
JavaScript原型链prototype属性和方法实例详解
详细介绍javascript使用prototype实现OOP继承的方法
The above is the detailed content of Detailed explanation of the use of prototype in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use
