Js中面向对象编程之继承的几种方式及理解

来源:互联网 发布:linux exec < > 编辑:程序博客网 时间:2024/05/17 18:47
window.onload = initall;function initall(){    var p = new Person("James","man")    p.sayHello();    p.say();    //Person.show();        var d = new Developer("Tom", "mail", "dev");    d.say();    d.job();        /* for(var attr in Person.prototype){        Tester.prototype[attr] = Person.prototype[attr];    } */        var t = new Tester("Jane","test dept....");    t.sayHello();    t.test();    t.saySex();}function Person(name,sex){this.name = name;this.sex = sex;var privateObj = "privateInfo";//js中的私有变量this.say = function(){console.log("say==",privateObj);}}/* js中设置静态变量和静态方法Person.staticObj = "staticInfo";Person.show = function(){console.log("show==",this.staticObj);} *//* sayHello 为js重的成员方法 */Person.prototype.sayHello = function(){console.log("sayHello name==",this.name);}//方法yi 使用call方法function Developer(name,sex,dept){Person.call(this,name,sex);this.dept = dept;this.job = function(){console.log("job==",this.dept);}}//使用call方法的弊端是浪费资源,每次new 一个子对象都会调用一遍call方法//方法二 使用原型prototypefunction Tester(name,dept){this.name = name;this.dept = dept;this.test = function(){console.log("test==",this.dept);}}Tester.prototype = new Person();//原型继承也有弊端,//一是子类通过prototype定义方法会覆盖父类同名方法,//二是父类构造函数无法带参数//例Tester.prototype = new Person(this.name);//子类实例化的对象是取不到父类name值的Tester.prototype.sayHello  = function(){//会覆盖父类Person重的sayHelloconsole.log("tester ... sayhello");}//解决办法是遍历父类中的属性,如果子类中有和父类同名的方法 则父类方法赋值给子类for(var attr in Person.prototype){        Tester.prototype[attr] = Person.prototype[attr];    }


0 0