


Property description of JavaScript prototype object_javascript skills
一、什么是JavaScript中对象的prototype属性
JavaScript中对象的prototype属性,是用来返回对象类型原型的引用的。我们使用prototype属性提供对象的类的一组基本功能。并且对象的新实例会”继承”赋予该对象原型的操作。但是这个prototype到底是怎么实现和被管理的呢?
对于对象的prototype属性的说明,JavaScript手册上如是说:所有 JavaScript内部对象都有只读的 prototype 属性。可以向其原型中动态添加功能(属性和方法),但该对象不能被赋予不同的原型。然而,用户定义的对象可以被赋给新的原型。
在JavaScript中,prototype对象是实现面向对象的一个重要机制。每个函数就是一个对象(Function),函数对象都有一个子对象prototype对象,类是以函数的形式来定义的。prototype表示该函数的原型,也表示一个类的成员的集合。在通过new创建一个类的实例对象的时候,prototype对象的成员都成为实例化对象的成员。
1、该对象被类所引用,只有函数对象才可引用;
2、在new实例化后,其成员被实例化,实例对象方可调用。
同时,函数是一个对象,函数对象若直接声明成员,不用被实例化即可调用。
JavaScript通过一种链接机制来支持继承,而不是通过完全面向对象语言(如Java)所支持的基于类的继承模型。每个JavaScript对象都有一个内置的属性,名为prototype。prototype属性保存着对另一个JavaScript对象的引用,这个对象作为当前对象的父对象。
When a function or attribute of an object is referenced through dot notation, if the function or attribute does not exist on the object, the prototype attribute of the object will be used. When this occurs, the object referenced by the object's prototype property is checked to see if the requested property or function is present. If the object referenced by the prototype attribute does not have the required function or attribute, the prototype attribute of this object (the object referenced by the prototype attribute) will be further checked and searched up the chain until the requested function or attribute is found, or the requested function or attribute is reached. The end of the chain. If the end of the chain has been reached and has not been found, undefined is returned.In this sense, this inheritance structure should be more of a "has a" relationship rather than an "is a" relationship
God, I don't understand anything, what should I do? It seems to make me awesome, but to be honest, I can’t understand it either! ^_^ ^_^ ^_^
2. Application examples of prototype attributes
Our common classes include: array variables (Array), logical variables (Boolean), date variables (Date ), structure variables (Function), numerical variables (Number), object variables (Object), string variables (String), etc., and related class methods are also often used by programmers (here we need to distinguish between classes Pay attention to the method of sending attributes), such as the push method of arrays, the get series method of dates, the split method of strings, etc.
But in the actual programming process, do you feel the shortcomings of the existing methods? The prototype method came into being! Below, we will explain the specific use of prototype from shallow to deep through examples:
Let’s look at a silly example first:
JavaScript code
function func(){
func.prototype.name = “prototype of func”;
}
var f = new func();
alert(f.name); //prototype of func
First create a func object and set the name attribute, instantiate f;
1. A few simple examples:
(1) Number addition:
JavaScript code
Number.prototype.add=function(num){
return (this num); //This here points to Number
};
alert((3).add(15));//18
(2) Boolean.rev() : Function, negation of Boolean variables
Implementation method: Boolean.prototype.rev = function(){return(!this);}
Test: alert((true).rev()) -> Display false
2. Implementation and enhancement of existing methods. First introduction to prototype:
(1) Array.push(new_element)
Function: Add a new element at the end of the array
Implementation method:
Array.prototype.push = function(new_element){
this[this.length]=new_element;
return this.length;
}
Let us further enhance him so that he can do it once Add multiple elements!
Implementation method:
Array.prototype.pushPro = function() {
var currentLength = this.length;
for (var i = 0; i < arguments.length; i ) {
This[currentLength i] = arguments[i];
}
return this.length;
}
It shouldn’t be difficult to understand, right? By analogy, you can consider how to delete any number of elements at any position by enhancing Array.pop (the specific code will not be detailed)
3. Implementation of new functions, in-depth prototype: What is used in actual programming is definitely not only the enhancement of existing methods, but also more functional requirements. Below I will give two examples of using prototypes to solve practical problems:
(1) String.left()
Problem: Anyone who has used VB should know the left function, which takes n characters from the left side of a string. However, the disadvantage is that both full-width and half-width are regarded as one character, which makes it impossible to intercept in a mixed layout of Chinese and English. Long string
Function: intercept n characters from the left side of the string, and support the distinction between full-width and half-width characters
Implementation method:
String.prototype.left = function(num,mode){
if(!/d /.test(num))return(this);
var str = this.substr(0,num);
if(!mode) return str;
var n = str .Tlength() – str.length;
num = num – parseInt(n/2);
return this.substr(0,num);
}
Test: alert(“aa Laaa".left(4)) -> Display aa lala
alert("aalalaaa".left(4,true)) -> Display aa lala
This method uses the above As for the String.Tlength() method mentioned, some good new methods can also be combined between custom methods!
(2) Date.DayDiff()
Function: Calculate the interval (year, month, day, week) between two date variables
Implementation method:
Date.prototype.DayDiff = function(cDate,mode){
cDate.getYear(); var base =60* 60*24*1000;
var result = Math.abs(this – cDate);
switch(mode){
case “y”:
result/=base*365;
break;
case “m”:
result/=base*365/12;
break;
case “w”:
result/=base*7;
break;
default:
result/=base;
break;
}
return(Math.floor(result));
}
Test: alert((new Date( )).DayDiff((new Date(2002,0,1)))) -> Display 329
alert((new Date()).DayDiff((new Date(2002,0,1)),” m”)) -> Display 10
Of course, it can also be further expanded to get the response hours, minutes, or even seconds.
(3) Number.fact()
Function: Factorial of a certain number
Implementation method:
Number.prototype.fact=function(){
var num = Math.floor( this);
if(num<0)return NaN;
if(num==0 || num==1)
return 1;
else
return (num*(num -1).fact());
}
Test: alert((4).fact()) -> Display 24
This method mainly shows that the recursive method is also used in the prototype method It works!
Example:
Get the maximum value of the array:
JavaScript code
var oArr=new Array(); prototype.MAX=function(){
var i,max=this[0];
for(i=1;i
} }
}
return max;
}
alert(oArr.MAX());
The instance is user-defined Class addition method:
JavaScript code
function TestObject()
{
this.m_Name = “ffffffffff”;
}
TestObject.prototype.ShowName = function()
{
alert(this.m_Name);
};
var f=new TestObject();
f.ShowName();
Update the prototype of the custom class:
JavaScript code
function TestObjectA()
{
this.MethodA = function()
{
alert('TestObjectA.MethodA()');
}
}
function TestObjectB()
{
this.MethodB = function()
{
alert('TestObjectB.MethodB()');
}
}
TestObjectB.prototype = new TestObjectA();
I heard that this is a misunderstood inheritance; I will learn it slowly in the future.
Look at another example, I think you and I have gone crazy:
JavaScript code
function RP()
{
RP.PropertyA = 1;
RP. MethodA = function()
{ alert(“RP.MethodA”);
};
this.PropertyA = 100;
this.MethodA = function()
{ 🎜>{
alert(“RP.prototype.MethodA”);
};
//The following is executed
rp = new RP();
alert(RP.PropertyA);/ /The warning result is: 1
RP.MethodA();//The warning result is: RP.MethodA
alert(rp.PropertyA);//The warning result is: 100
rp.MethodA(); //The warning result is: this.MethodA
delete RP.PropertyA;
alert(RP.PropertyA); //The warning result is: undefined
delete rp.PropertyA;
alert( rp.PropertyA);//The warning result is: 100
delete rp.MethodA;
rp.MethodA();//The warning result is: RP.prototype.MethodA
Look at another one with parameters , calculate the area of a circle:
JavaScript code
; This.y = y; There is no structural difference between the definition of and the definition of a function, so it can be said that all functions have such a hidden attribute. */ 5);
alert(parseInt(Circ.area()));

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



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 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

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 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 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

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

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).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
