js的prototype属性介绍

1、介绍:prototype 用给对象添加属性或方法;

(注意:prototype是全局属性,适用于所有的js对象)

2、语法:添加属性:object.prototype.name="张三";添加方法:object.prototype.addFun=function(){};

3、首先了解类的概念:JavaScript 本身是一种面向对象的语言,它所涉及的元素根据其属性的不同都依附于某一个特定的类。我们所常见的类包括:数组变量(Array)、逻辑变量(Boolean)、日期变量(Date)、结构变量(Function)、数值变量(Number)、对象变量(Object)、字符串变量(String) 等,而相关的类的方法,也是程序员经常用到的(在这里要区分一下类的注意和属性发方法),例如数组的push方法、日期的get系列方法、字符串的split方法等等,

但是在实际的编程过程中不知道有没有感觉到现有方法的不足?prototype 方法应运而生!下面,将通过实例由浅入深讲解 prototype 的具体使用方法:

1、简单的列子,了解prototype;

(1)Number.add(num):数字相加;

    实现方法:Number.prototype.add=function(num){

                            return(this+num)

                        };

       试验:alert((5).add(13))

一次增加多个元素!

实现方法:

Array.prototype.pushPro = function() {

var currentLength = this.length;

for (var i = 0; i < arguments.length; i++) {

this[currentLength + i] = arguments[i];

}

return this.length;

}

  应该不难看懂吧?以此类推,你可以考虑一下如何通过增强 Array.pop 来实现删除任意位置,任意多个元素(具体代码就不再细说了)

(2) String.length

作用:这实际上是 String 类的一个属性,但是由于 JavaScript 将全角、半角均视为是一个字符,在一些实际运用中可能会造成一定的问题,现在我们通过 prototype 来弥补这部不足。

实现方法:

String.prototype.cnLength = function(){

var arr=this.match(/[^\x00-\xff]/ig);

return this.length+(arr==null?0:arr.length);

}

试验:alert("EaseWe空间Spaces".cnLength()) -> 显示 16

这里用到了一些正则表达式的方法和全角字符的编码原理,由于属于另两个比较大的类别,本文不加说明,请参考相关材料。

3、新功能的实现,深入 prototype:在实际编程中所用到的肯定不只是已有方法的增强,更多的实行的功能的要求,下面我就举两个用 prototype 解决实际问题的例子:

(1) String.left()

问题:用过 vb 的应该都知道left函数,从字符串左边取 n 个字符,但是不足是将全角、半角均视为是一个字符,造成在中英文混排的版面中不能截取等长的字符串

作用:从字符串左边截取 n 个字符,并支持全角半角字符的区分

实现方法:

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

}

试验:

alert("EaseWe空间Spaces".left(8)) -> 显示 EaseWe空间

alert("EaseWe空间Spaces".left(8,true)) -> 显示 EaseWe空

本方法用到了上面所提到的String.Tlength()方法,自定义方法之间也能组合出一些不错的新方法呀!

(2) Date.DayDiff()

作用:计算出两个日期型变量的间隔时间(年、月、日、周)

实现方法:

Date.prototype.DayDiff = function(cDate,mode){

try{

cDate.getYear();

}catch(e){

return(0);

}

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

}

试验:alert((new Date()).DayDiff((new Date(2002,0,1)))) -> 显示 329

alert((new Date()).DayDiff((new Date(2002,0,1)),"m")) -> 显示 10

当然,也可以进一步扩充,得出响应的小时、分钟,甚至是秒。

(3) Number.fact()

作用:某一数字的阶乘

实现方法:

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());

}

试验:alert((4).fact()) -> 显示 24

这个方法主要是说明了递归的方法在 prototype 方法中也是可行的!

JavaScript能够实现的面向对象的特征有:

·公有属性(public field)

·公有方法(public Method)

·私有属性(private field)

·私有方法(private field)

·方法重载(method overload)

·构造函数(constructor)

·事件(event)

·单一继承(single inherit)

·子类重写父类的属性或方法(override)

·静态属性或方法(static member)

例子一(JavaScript中允许添加行为的类型):可以在类型上使用proptotype来为类型添加行为。这些行为只能在类型的实例上体现。 JS中允许的类型有Array, Boolean, Date, Enumerator, Error, Function, Number, Object, RegExp, String


Object.prototype.Property = 1; 

Object.prototype.Method = function () 

alert(1); 

var obj = new Object(); 

alert(obj.Property); 

obj.Method(); 


Object.prototype.Property = 1;

Object.prototype.Method = function (){ alert(1);} 

var obj = new Object();

alert(obj.Property);

obj.Method();

例子二(prototype使用的限制):在实例上不能使用prototype,否则发生编译错误


var obj = new Object(); 

obj.prototype.Property = 1; //Error 

//Error 

obj.prototype.Method = function() 

alert(1); 


var obj = new Object();obj.prototype.Property = 1; //Error//Errorobj.prototype.Method = function(){ alert(1);}

例子三(如何定义类型上的静态成员):可以为类型定义“静态”的属性和方法,直接在类型上调用即可


Object.Property = 1; 

Object.Method = function() 

alert(1); 

alert(Object.Property); 

Object.Method(); 


Object.Property = 1;Object.Method = function(){ alert(1);} alert(Object.Property);Object.Method();

例子五():这个例子演示了通常的在JavaScript中定义一个类型的方法

代码如下:


function Aclass() 

this.Property = 1; 

this.Method = function() 

alert(1); 

var obj = new Aclass(); 

alert(obj.Property); 

obj.Method(); 


function Aclass(){this.Property = 1;this.Method = function(){ alert(1);}}var obj = new Aclass();alert(obj.Property);obj.Method();

例子六(JavaScript中允许添加行为的类型):可以在外部使用prototype为自定义的类型添加属性和方法。

代码如下:


function Aclass() 

this.Property = 1; 

this.Method = function() 

alert(1); 

Aclass.prototype.Property2 = 2; 

Aclass.prototype.Method2 = function 

alert(2); 

var obj = new Aclass(); 

alert(obj.Property2); 

obj.Method2(); 


function Aclass(){this.Property = 1;this.Method = function(){ alert(1);}}Aclass.prototype.Property2 = 2;Aclass.prototype.Method2 = function{ alert(2);}var obj = new Aclass();alert(obj.Property2);obj.Method2();

例子八():可以在对象上改变属性。(这个是肯定的)也可以在对象上改变方法。(和普遍的面向对象的概念不同)

代码如下:


function Aclass() 

this.Property = 1; 

this.Method = function() 

alert(1); 

var obj = new Aclass(); 

obj.Property = 2; 

obj.Method = function() 

alert(2); 

alert(obj.Property); 

obj.Method(); 


function Aclass(){this.Property = 1;this.Method = function(){ alert(1);}}var obj = new Aclass();obj.Property = 2;obj.Method = function(){ alert(2);}alert(obj.Property);obj.Method();

例子九():可以在对象上增加属性或方法

代码如下:


function Aclass() 

this.Property = 1; 

this.Method = function() 

alert(1); 

var obj = new Aclass(); 

obj.Property = 2; 

obj.Method = function() 

alert(2); 

alert(obj.Property); 

obj.Method(); 


function Aclass(){this.Property = 1;this.Method = function(){ alert(1);}}var obj = new Aclass();obj.Property = 2;obj.Method = function(){ alert(2);}alert(obj.Property);obj.Method();

例子十(如何让一个类型继承于另一个类型):这个例子说明了一个类型如何从另一个类型继承。

代码如下:


function AClass() 

this.Property = 1; 

this.Method = function() 

alert(1); 

function AClass2() 

this.Property2 = 2; 

this.Method2 = function() 

alert(2); 

AClass2.prototype = new AClass(); 

var obj = new AClass2(); 

alert(obj.Property); 

obj.Method(); 

alert(obj.Property2); 

obj.Method2(); 


function AClass(){ this.Property = 1; this.Method = function() { alert(1); }} function AClass2(){ this.Property2 = 2; this.Method2 = function() { alert(2); }}AClass2.prototype = new AClass(); var obj = new AClass2();alert(obj.Property);obj.Method();alert(obj.Property2);obj.Method2();

 例子十一(如何在子类中重新定义父类的成员):这个例子说明了子类如何重写父类的属性或方法。

代码如下:


function AClass() 

this.Property = 1; 

this.Method = function() 

alert(1); 

function AClass2() 

this.Property2 = 2; 

this.Method2 = function() 

alert(2); 

AClass2.prototype = new AClass(); 

AClass2.prototype.Property = 3; 

AClass2.prototype.Method = function() 

alert(4); 

var obj = new AClass2(); 

alert(obj.Property); 

obj.Method(); 

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,159评论 0 2
  • 单例模式 适用场景:可能会在场景中使用到对象,但只有一个实例,加载时并不主动创建,需要时才创建 最常见的单例模式,...
    Obeing阅读 6,375评论 1 10
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 12,383评论 2 17
  • 北京2018年4月1日上午,NBA常规赛勇士客战国王的比赛中,发生了令人痛心不已的一幕。比赛进行到第三节还有41...
    Curry_宇阅读 5,010评论 1 1
  • 刚刚读了一篇文章,论如何在社交时代谈到男朋友。 明天是情人节,这篇文章真是恰逢时机。让作为单身狗的我心念一动。 文...
    33不喝酒阅读 2,338评论 0 0