日期:2014-05-16  浏览次数:20357 次

javascript 面向对象 prototype原型

//定义构造函数,规定每个js对象必须定义Create构造方法

function New(aClass,params){
?function _new(){

? if(aClass.Create)
?????aClass.Create.apply(this,params);
?}
?_new.prototype = aClass;
?return new _new();
}?


function Extents(BaseClass,SubClass){
?function _extends(){
??for(var member in SubClass){
???this[member] = SubClass[member];// 把子类中方法,属性 复制到“临时类中”
??}
?}
?_extends.prototype = BaseClass;//给临时类得prototype赋值,指向基类?? 这样临时就有了基类的所有特性。
?return new _extends(); //返回临时对象。
}

var Person = Extents({},{
??Create:function(name,age){this.name=name;this.age=age;},
??sayHello:function(){alert("my name is "+ this.name+" and age is "+ this.age+? ". i like making friends especially girl friends");}
?});

var p = New(Person,["刘志全",23]);
p.sayHello();


var Engineer = Extents(Person,{
?Create:function(name,age,lan,salary){
???????????Person.Create.call(this,name,age) ;
???????????this.lan = lan;
???????????this.salary = salary;
??????????},
?
?introduce:function(){
???document.write("i am a? "+ this.lan + " programer? and? the salary is "+ this.salary );
??}
?
?});

var engineer = New(Engineer,["全哥",23,"java,php,javascript and android","secret"] )

engineer.sayHello();
engineer.introduce();