Home Web Front-end JS Tutorial Examples of instance objects and prototype objects in JavaScript_Basic knowledge

Examples of instance objects and prototype objects in JavaScript_Basic knowledge

May 16, 2016 pm 03:11 PM
javascript prototype Example instance object object

First of all, declare: Every object in JavaScript has a constructor attribute and a prototype attribute. constructor points to the object's constructor, and prototype points to the prototype object of the object instance created using the constructor.

function Person(){ 
  
 } 
var person = new Person(); 
 
Person.prototype = { 
 constructor : Person, 
 name : 'zxs', 
 age : 24, 
 sayName : function(){alert(this.name)} 
 } 
  
person.sayName(); 
Copy after login

An error will be reported in this code, sayName() is not defined. According to JavaScript Advanced Programming Second Edition, it is because the overridden prototype cuts off the connection between the constructor and the original prototype. But let’s adjust the order of the above statements. As follows:

function Person(){ 
 } 
//var person = new Person(); 
Person.prototype = { 
 constructor : Person, 
 name : 'zxs', 
 age : 24, 
 sayName : function(){alert(this.name)} 
} 
/*===========================================================*/ 
var person = new Person(); 
/*===========================================================*/ 
 person.sayName(); // zxs 
alert(person.constructor) //function Object() { [native code]} or function Person() {} 取决与蓝色的语句是否有效 
Copy after login

Pay attention to the statements between the equal signs in the two pieces of code above. If you write the code in the order of the second paragraph, "zxs" will be output. This result shows that the error reported in the first case does not mean that it is caused by cutting off the connection between the constructor and the original idea.

Person.prototype = {} 
Copy after login

It is originally a way to define objects, and the constructor property of each object in JavaScript points to the Object constructor by default. This is not difficult to show that rewriting the prototype object does cut off the connection between the constructor and the original prototype. connection, but it does not mean that person cannot access the sayName() function after this connection is severed.

Now there is this assumption: the prototype object pointed to by the prototype attribute of the function is not exactly the same as the prototype object we display to create a new one. When we call a function, a prototype object will be created. At this time, we will first check whether its prototype object exists in the current environment. If it does not exist in the program, create one. If it exists in the environment, we will search for their properties and methods. Finally, A prototype object is returned based on the search result. The properties and methods in this object always use the properties and methods in the default prototype first, that is, the properties and methods defined in the constructor. When the called method or property does not exist in the default prototype, the properties and methods defined in Person.prototype = {} are used.

Javascript is an interpreted language, and statements are executed sequentially. In the first piece of code, when we use the new keyword to create a new object, Person.prototype = {} is not executed, which means that The methods and properties defined in it cannot be found in the current execution environment, and the method does not exist in the constructor, so an error occurs. Just like a variable, it cannot be used when the program is not executed when assigning a value to it. In the second paragraph, the called method already exists in the environment, and the prototype object of the constructor has been created, so the result can be obtained.

Look at the following program:

////////////////////////////////////////////////////////////////////////// 
 
function Person(){} 
 
/*===========================================================*/ 
 
 var person = new Person(); 
Person.prototype.name = 'song'; 
 
/*===========================================================*/ 
 
//Person.prototype.sayName = function(){alert(this.name)}; 
Person.prototype = { 
constructor : Person, 
name : 'zxs', 
age : 24, 
sayName : function(){alert(this.name)} 
} 
person.sayName(); // error 
 
////////////////////////////////////////////////////////////////////////// 
 
function Person(){  } 
/*var person = new Person();*/ 
Person.prototype.name = 'song';  
/*Person.prototype.sayName = function(){alert(this.name)};*/ 
Person.prototype = {   
constructor : Person, 
  name : 'zxs', 
  age : 24, 
  sayName : function(){alert(this.name)} 
} 
 
/*===========================================================*/ 
var person = new Person(); 
 
/*===========================================================*/ 
person.sayName(); // zxs 
Copy after login

It can be seen from here that using Person.prototype.name = '', the object can be accessed no matter where it is created. If there is both an object literal and a prototype object defined by this method, the later defined object will be used. as final value. And after using an object literal definition for a prototype object, the definition must appear before the statement that creates the object before it can be accessed.

Instances cannot access properties and methods in the prototype object, not least because overriding the prototype object cuts off the connection between the constructor and the original prototype.

function Person(){  
    
  }  
var person = new Person();  
  
Person.prototype = {  
  //constructor : Person,  
  name : 'zxs',  
  age : 24,  
  sayName : function(){alert(this.name)}  
  }  
    
person.sayName();  
Copy after login

The prototype of the constructor in the above code is empty when instantiating the object, and it does not have any properties other than the default properties. Overriding the constructor's prototype does sever the connection between the constructor and the original prototype.

After using the new operator, the properties and methods in the prototype object of the constructor have been added to the person object. Because the above method is not dynamic in adding new properties and methods to the function prototype, person cannot access the newly added properties and methods.

After rewriting the prototype object, it is like the following code:

var o = { 
  name : 'zxs' 
  } 
   
var obj = o; 
o = {} 
console.log(o.name);  
Copy after login

The output value at this time is undefined, because the object is a reference type, "=" is the assignment operator, and the order of operations is from right to left. o={} means that the pointing of o has changed and is an empty object.
The difference between Person.prototype.mothed = function() {} and Person.prototype={mothed:function(){}} is the same as arr = [] and arr.push(). The former modifies itself, while the latter modifies itself. Completely transform yourself.

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
1255
24
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 convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

Introduction to the new map of Genshin Impact version 4.4 Introduction to the new map of Genshin Impact version 4.4 Jan 31, 2024 pm 06:36 PM

Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Analyze the differences between heap and stack in Java and their application scenarios Analyze the differences between heap and stack in Java and their application scenarios Feb 24, 2024 pm 11:12 PM

The difference between Java heap and stack and application scenario analysis require specific code examples. In Java programs, heap and stack are two commonly used data structures, and they assume different roles and functions in memory. Understanding the difference between heap and stack is crucial to writing efficient Java programs. First, let's take a look at the Java heap. The heap is an area used to store objects. All objects created in the program are stored in the heap. The heap is where memory is dynamically allocated and released while the program is running. It is not subject to any restrictions and can be automatically allocated and released as needed.

See all articles