复制代码 代码如下:
//var people={name:xiong,age:15};
//var person=function(user,age){
// this.name=user;
// this.age=age;
// this.say=function(){alert(i am +this.name+\n+this.age);}
//}
//var chairman=function(name,salary){
// person.call(this,name);
// }
//var bill=new person(bill,15);
//var hu=new chairman(hu jintao);
//person.prototype.eat=function(){
// alert(i'm eating);
// }
//bill.eat();
function person(name) //基类构造函数
{
this.name = name;
};
person.prototype.sayhello = function() //给基类构造函数的 prototype 添加方法
{
alert(hello, i'm + this.name);
};
function employee(name, salary) //子类构造函数
{
person.call(this, name); //调用基类构造函数
this.salary = salary;
};
function xiong(name,age){
employee.call(this,name);
}
employee.prototype = new person(); //建一个基类的对象作为子类原型的原型,这里很有意思
xiong.prototype=new employee();
employee.prototype.showmethemoney = function() //给子类添构造函数的 prototype 添加方法
{
alert(this.name + $ + this.salary);
};
var billgates = new person(bill gates); //创建基类 person 的 billgates 对象
var stevejobs = new employee(steve jobs, 1234); //创建子类 employee 的 stevejobs对象
var hiakuotiankong=new xiong(海阔天空);
var benbenxiong=new xiong(笨笨熊);
// billgates.sayhello(); //通过对象直接调用到 prototype 的方法
// hiakuotiankong.sayhello(); //通过子类对象直接调用基类 prototype 的方法,关注!
benbenxiong.sayhello=function(){ //掩盖了原型的 sayhello 方法
alert(haha,i'm+this.name);
}
benbenxiong.sayhello();
// stevejobs.showmethemoney(); //通过子类对象直接调用子类 prototype 的方法
// alert(billgates.sayhello == stevejobs.sayhello); //显示:true,表明 prototype 的方法是共享的
xiong.prototype.goodbye=function(){
alert(this.name+bye-bye);
}
benbenxiong.goodbye();
在 javascript 中,prototype 不但能让对象共享自己财富,而且 prototype 还有寻根问祖的
天性,从而使得先辈们的遗产可以代代相传。当从一个对象那里读取属性或调用方法时,如果该对象自
身不存在这样的属性或方法,就会去自己关联的 prototype 对象那里寻找;如果 prototype 没有,又会
去 prototype 自己关联的前辈 prototype 那里寻找,直到找到或追溯过程结束为止。
在 javascript 内部,对象的属性和方法追溯机制是通过所谓的 prototype 链来实现的。当用 new
操作符构造对象时,也会同时将构造函数的 prototype 对象指派给新创建的对象,成为该对象内置的原
型对象。对象内置的原型对象应该是对外不可见的,尽管有些浏览器(如 firefox)可以让我们访问这个
内置原型对象,但并不建议这样做。内置的原型对象本身也是对象,也有自己关联的原型对象,这样就
形成了所谓的原型链。
在原型链的最末端,就是 object 构造函数 prototype 属性指向的那一个原型对象。这个原型对象
是所有对象的最老祖先,这个老祖宗实现了诸如 tostring 等所有对象天生就该具有的方法。其他内置
构造函数,如 function, boolean, string, date 和 regexp 等的 prototype 都是从这个老祖宗传承下
来的,但他们各自又定义了自身的属性和方法,从而他们的子孙就表现出各自宗族的那些特征。