js原型鏈繼承及調用父類方法


方法1:
 1  var Parent= function () {
 2 
 3     };
 4 
 5     Parent.prototype.process = function(){
 6         alert('parent method');
 7     };
 8 
 9     var Child= function () {
10         Parent.call(this);
11     };
12 
13     Child.prototype = new Parent();
    Child.prototype.constructor=Child;
14 Child.prototype.process = function(){ 15 Parent.prototype.process.apply(this, arguments);16 alert('child method'); 17 }; 18 19 var childVar = new Child(); 20 childVar.process();

 方法2

function(){
    //創建一個人員類
    function Person(name){
        this.name = name;
    }
    //創建教師類
    function Teacher(name,books){
        //call方法可以將一個函數的對象上下文從初始化變成有this來決定
        //調用Person的構造函數,因為Person沒用new 所以他是個空對象
        //相當於java中的super函數
        Person.call(this,name);
        this.books = books;
    }
    //使老師類繼承人員類
    Teacher.prototype = new Person();
    Teacher.prototype.constructor = Teacher;
    Teacher.prototype.getBook = function(){
        return this.name +" "+ this.books;
    }
    //測試
    var jim = new Teacher("JIM","EXTJS4");
    //alert(jim.getBook());
    
    /**
     * 創建Extend函數為了程序中石所有的集成操作
     */
    function extend(subClass,superClass){
        //1.叫子類原型類屬性等於父類的原型屬性
        //初始化一個中間空對象,為了轉換主父類關系
        var F = function(){};
        F.prototype = superClass.prototype;
        //2.讓子類集成F
        subClass.prototype = new F();
        subClass.prototype.constructor = subClass;
        //3.為子類增加屬性superClass
        subClass.superClass = superClass.prototype;
        //4.增加一個保險,就算你是的原型類是超類(Object) 那么也要把你的構造函數級別講下來
        if(superClass.prototype.constructor == Object.prototype.constructor){
            superClass.prototype.constructor = superClass;
        }
    }
    //測試
    function Author(name,books){
        Author.superClass.constructor.call(this,name);
        
        this.books = books;
        this.getBook = function(){
            
        console.log(Author.superClass.getBook.apply(this, arguments)) ;
        
            return this.name +" "+ this.books;
        }
    }
    //繼承
    extend(Author,Teacher);
    
    var peter = new Author("YUNFENGCHENG","JAVASCIPT");
   
    console.log(peter.getBook());
    ;
})()

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM