javascript prototype原型操作笔记
2024-05-06 14:12:32
供稿:网友
代码如下:
//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 没有,又会