Home > Web Front-end > JS Tutorial > Property description of JavaScript prototype object_javascript skills

Property description of JavaScript prototype object_javascript skills

WBOY
Release: 2016-05-16 18:32:29
Original
1078 people have browsed it

一、什么是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 if(max max=this[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()));

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template