JavaScript object-oriented - rewriting of prototypes
In the previous article, we introduced the memory model of the prototype and analyzed the status of the prototype at each stage through 4 pictures. Below we will first introduce some commonly used prototype and object property detection methods. Let’s take the Person class from the previous article as an example. The code to create the Person class is as follows:
function Person(){}; Person.prototype.name = "Leon"; Person.prototype.age = 22; Person.prototype.say = fucntion(){ alert(this.name + "," + this.age); } var p1 = new Person(); var p2 = new Person(); p2.name = "Ada"; p1.say(); p2.say();
1. Detect whether an object is the prototype of a certain function
alert(Person.prototype.isPrototypeOf(p1)); //true
This method can detect Whether the prototype of p1 is Person.
2. Detect the constructor of an object
alert(p1.constructor == Person); //true
3. Detect whether an attribute is your own attribute
alert(p1.hasOwnProperty("name")); //false alert(p2.hasOwnProperty("name")); //true
Object p1 does not have a name attribute in its own space. So return false. The object p2 reassigns the name attribute, and the name attribute exists in its space, so it returns true.
4. Delete attributes in your own space through delete
delete p2.name; p2.say(); alert(p2.hasOwnProperty("name")); //false
We can use delete to delete an attribute in the object's own space, as shown in the above code.
5. Use the in attribute to detect whether an object contains a certain attribute in the prototype or itself
alert("name" in p1); //在原型中有,所以为true alert("name" in p2); //在自己的空间中有,所以为true
If an attribute is not found in the prototype or its own space, the result obtained It's false.
6. Custom method to detect whether a certain attribute exists in the prototype
function hasPrototypeProperty(obj,prop){ return(!obj.hasOwnProperty(prop) && (prop in obj)); }
In the above code, we have customized a method to detect whether a certain attribute exists in the prototype, which can be used as follows This method:
alert(hasPrototypeProperty(p1,"name")); //true alert(hasPrototypeProperty(p2,"name")); //false
Because the name attribute of the p1 object exists in the prototype, it returns true, and the name attribute of the p2 object is in its own space, so it returns false.
Rewriting the prototype
If we write the code as before, there will be a large number of Person.prototype.xxx statements, which is not convenient for us to read and understand. We can rewrite the prototype in a Json-like format. The code is as follows:
//重写原型 Person.prototype = { name:"Leon", age:22, say:function(){ alert(this.name+ "," + this.age); } } var p1 = new Person(); p1.say();
After using the above method to rewrite the prototype, since the prototype has been rewritten and not specified through Person.prototype, at this time The constructor no longer points to Person, but to Object.
alert(p1.constructor == Person); //false
If the constructor is really important to your program, you can declare the prototype pointer in json.
Person.prototype = { constructor:Person, //手动指定constructor name:"Leon", age:22, say:function(){ alert(this.name+ "," + this.age); } }
Problems with prototype rewriting
When rewriting the prototype, we may encounter some of the following problems. Next, let's first look at a piece of prototype rewritten code that will cause problems, and then analyze the memory model at each stage in the code. The code is as follows:
// 创建Person类 function Person(){} var p1 = new Person(); //在Person的原型上添加了sayHi()方法 Person.prototype.sayHi = function(){ alert(this.name + "Hi!"); } p1.sayHi(); //输出: undefined:hi! // 对Person原型进行重写 Person.prototype = { constructor:Person, //手动指定constructor name:"Leon", age:22, say:function(){ alert(this.name+ "," + this.age); } } var p2 = new Person(); p2.sayHi(); p2.say();//正确 p1.say();//报错
In the above code, we first create a Person class. At this time, the memory model of the Person prototype is as shown below:
Then we created the p1 object, and then added a sayHi() method to the Person prototype. At this time, the memory model of the Person prototype is as shown below:
var p1 = new Person(); //在Person的原型上添加了sayHi()方法 Person.prototype.sayHi = function(){ alert(this.name + "Hi!"); } p1.sayHi(); //输出: undefined:hi!
Pay attention to the current memory model, because in this state, There is no name attribute in the p1 object's own space or in the Person prototype, so when the p1.sayHi() method is executed, the this.name attribute is undefined, and the final output result is undefined:hi!.
Next we rewrote the Person prototype and added some properties and methods to the prototype.
// 对Person原型进行重写 Person.prototype = { constructor:Person //手动指定constructor name:"Leon", age:22, say:function(){ alert(this.name+ "," + this.age); } } p1.sayHi(); //输出: undefined:hi!
The prototype memory model at this time is as shown below:
After the prototype is rewritten, JavaScript will allocate a new memory for the prototype, Person class Points to the new prototype object, and the _proto_ attribute of the originally created p1 object still points to the previous prototype object.
At this time, if we execute p1.sayHi(), the program will not report an error, but the execution result is still undefined:hi!, because there is no name attribute in the p1 object and the prototype it points to. .
Finally, after prototype rewriting, we create object p2.
var p2 = new Person(); p2.sayHi();
The prototype memory model at this time is as shown below:
The _proto_ attribute of the newly created p2 object points to the rewritten Prototype object, if the p2.sayHi() method is executed at this time, there will be no sayHi() method on the p2 object and the prototype it points to, so the program will report an error.
If the p1.say() method is executed at this time, since there is no say() method in p1 or the prototype it points to, the program will report an error.
Through the analysis of the prototype memory model above, we can know that the prototype rewriting position will directly affect the properties and methods of the object. The properties and methods of objects created before rewriting and objects created after rewriting are different. the same. The memory model diagrams above must be kept in mind at all times.
The above is the content of JavaScript object-oriented prototype rewriting. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript
