JavaScript原型

四、原型的作用

JavaScript中原型有很广泛的用途,在此我们仅举两例,供大家参考。

1.格式化日期

在JavaScript中对日期格式化的支持不是很完善,需要我们自己弥补。但是用到日期格式化的地方又很多,这毕竟是个基础操作,那如何能够一劳永逸的解决这个问题呢?

 

①通过原型机制将格式化日期的函数添加到Date()函数对象上

代码如下:

// 对Date的扩展,将 Date 转化为指定格式的String

// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,

// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)

// 例子:

// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423

// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18

//var time1 = new Date().format("yyyy-MM-dd HH:mm:ss");   

//

//var time2 = new Date().format("yyyy-MM-dd");  

Date.prototype.Format = function(fmt) { // author: meizz

var o = {

"M+" : this.getMonth() + 1, // 月份

"d+" : this.getDate(), // 日

"h+" : this.getHours(), // 小时

"m+" : this.getMinutes(), // 分

"s+" : this.getSeconds(), // 秒

"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度

"S" : this.getMilliseconds()

// 毫秒

};

if (/(y+)/.test(fmt))

fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")

.substr(4 - RegExp.$1.length));

for ( var k in o)

if (new RegExp("(" + k + ")").test(fmt))

fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])

: (("00" + o[k]).substr(("" + o[k]).length)));

return fmt;

}

 

②将上述代码保存到js文件中

 

③使用时引入这个js 文件即可调用format()函数格式化日期

 

2.模拟继承

在JavaScript中没有类的概念,用于创建对象的构造器函数很类似于Java中的类。而面向对象中的很多思想在JavaScript中也只能模拟实现。

 

①情景举例

声明一个Person构造器函数和一个Student构造器函数。

function Person(theName,theAge){

this.theName = theName;

this.theAge = theAge;

}

function Student(theName,theAge,subject){

this.theName = theName;

this.theAge = theAge;

this.subject;

}

 

很明显,这两个函数从语义上来说存在着继承关系,学生是人的一种,Student对象应该是Person对象的实例。同时给姓名和年龄赋值的语句在两个函数中也是重复的。

所以模拟继承时我们需要解决两个问题:

i.将Student中的重复代码使用Person来代替

ii.让Student对象是Person的实例,即student instanceof Person要返回true

 

②提取重复代码

function Person(theName,theAge){

this.theName = theName;

this.theAge = theAge;

}

function Student(theName,theAge,subject){

Person.apply(this, arguments);

this.subject;

}

 

 

③instanceof

function Person(theName,theAge){

this.theName = theName;

this.theAge = theAge;

}

function Student(theName,theAge,subject){

Person.apply(this, arguments);

this.subject;

}

Student.prototype = Person.prototype;

var student = new Student("Tom", 20, "Java");

console.log(student);

console.log(student instanceof Person);

 

那么这是为什么呢?在JavaScript中,判断一个对象是否是某个构造器函数的实例,就是看分别沿着对象和函数的原型链能否找到同一个原型对象。

例如:student对象为什么能够是Object的实例呢?

console.log(student instanceof Object); //true

console.log(student.__proto__.__proto__ === Object.prototype); //true

 

那么现在student.__proto__和Person.prototype相等,student自然就可以是Person的实例了。

 

 

本教程由尚硅谷教育大数据研究院出品,如需转载请注明来源,欢迎大家关注尚硅谷公众号(atguigu)了解更多。