Javascript 之prototype属性
在js中,每个对象都有一个prototype属性:返回对象类型原型的引用。很拗口!习语“依葫芦画瓢”,这里的葫芦就是原型,那么“瓢.prototype” 返回的就是葫芦,或者“瓢.prototype= new 葫芦()”。
prototype的用途:
继承
有一个对象--子类:
function 子类() {
this.lastname = "Samuel";
}
有一个对象--父类:
function 父类() {
this.firstname = "Shen";
}
现在子类是有名无姓,父类是有姓无名,如果子类要有名有姓的话,只要说明--子类的原型是父类--就可以了,即子类继承自父类:
子类.prototype = new 父类();
至此,子类就不再是有名无姓了。
alert(子类.firstname + " " + 子类.lastname); //Samuel Shen
牵一发而动全身
既然prototype返回的是原型的引用,那么如果改变原型的话,所有继承自该原型的对象都将受到影响。
function Point(x,y) {
this.x = x;
this.y = y;
}
var p1 = new Point(1,2);
var p2 = new Point(3,4);
Point.prototype.z = 0; //动态为Point的原型添加了属性
alert(p1.z); //0
alert(p2.z); //0
/***************************************************************************/
function Person(name,sex) { //Person类的构造函数
this.name = name;
this.sex = sex;
}
Person.prototype.age = 12; //为Person类的prototype属性对应的prototype对象的属性赋值,
//相当于为Person类的父类添加属性
Person.prototype.print = function() { //为Person类的父类添加方法
alert(this.name+"_"+this.sex+"_"+this.age);
};
var p1 = new Person("name1","male"); //p1的age属性继承子Person类的父类(即prototype对象)
var p2 = new Person("name2","male");
p1.print(); //name1_male_12
p2.print(); //name2_male_12
p1.age = 34; //改变p1实例的age属性 p1属性在不指向Person的prototype属性
p1.print(); //name1_male_34
p2.print(); //name2_male_12
Person.prototype.age = 22; //改变Person类的超类的age属性
p1.print(); //name1_male_34(p1的age属性并
相关文档:
搞了大半天,总算弄明白了为何用document.body.clientHeight,document.body.offsetHeight都没有办
法获取网页可见区域的正确值,原来罪魁祸首是W3C定义的标准!!在新定义出来的标准下
document.documentElement.clientHeight在IE和火狐里都能获取正确值,下面一篇文章详细介绍了获取各种浏览器可见
窗口大小这方面的差 ......
创建一个日期对象:
var objDate=new Date([arguments list]);
参数形式有以下5种:
new Date("month dd,yyyy hh:mm:ss");
new Date("month dd,yyyy");
new Date(yyyy,mth,dd,hh,mm,ss);
new Date(yyyy,mth,dd);
new Date(ms); ......
<html>
<head>
<title>Javascript</title>
<script language="Javascript" type="text/javascript">
function callMethod()
{
/*http://localhost/waa/WebService.asmx为Servic ......
Javascript刷新页面的几种方法:
1 history.go(0)
2 location.reload()
3 location=location
4 location.assign(location)
5 document.execCommand('Refresh')
6 window.navigate(location)
7& ......
1、对象的继承,一般的做法是复制:Object.extend
prototype.js的实现方式是:
Object.extend = function(destination, source){
for (property in source) {
destination[property] = source[property];
}
return destination;
......