天天看點

js面向對象繼承的實作

出處1:http://yahaitt.iteye.com/blog/250338

出處2:JS如何建立對象及實作繼承[圖文] http://www.cnblogs.com/maxupeng/archive/2010/12/28/1918480.html

js繼承的實作

記錄自浪曦風中葉老師的JavaScript課堂 

js繼承有5種實作方式: 

1、繼承第一種方式:對象冒充 

  function Parent(username){ 

    this.username = username; 

    this.hello = function(){ 

      alert(this.username); 

    } 

  } 

  function Child(username,password){ 

    //通過以下3行實作将Parent的屬性和方法追加到Child中,進而實作繼承 

    //第一步:this.method是作為一個臨時的屬性,并且指向Parent所指向的對象, 

    //第二步:執行this.method方法,即執行Parent所指向的對象函數 

    //第三步:銷毀this.method屬性,即此時Child就已經擁有了Parent的所有屬性和方法 

    this.method = Parent; 

    this.method(username);//最關鍵的一行 

    delete this.method; 

    this.password = password; 

    this.world = function(){ 

      alert(this.password); 

  var parent = new Parent("zhangsan"); 

  var child = new Child("lisi","123456"); 

  parent.hello(); 

  child.hello(); 

  child.world(); 

2、繼承第二種方式:call()方法方式 

  call方法是Function類中的方法 

  call方法的第一個參數的值指派給類(即方法)中出現的this 

  call方法的第二個參數開始依次指派給類(即方法)所接受的參數 

  function test(str){ 

    alert(this.name + " " + str); 

  var object = new Object(); 

  object.name = "zhangsan"; 

  test.call(object,"langsin");//此時,第一個參數值object傳遞給了test類(即方法)中出現的this,而第二個參數"langsin"則指派給了test類(即方法)的str 

    Parent.call(this,username); 

3、繼承的第三種方式:apply()方法方式 

  apply方法接受2個參數, 

    A、第一個參數與call方法的第一個參數一樣,即指派給類(即方法)中出現的this 

    B、第二個參數為數組類型,這個數組中的每個元素依次指派給類(即方法)所接受的參數 

    Parent.apply(this,new Array(username)); 

4、繼承的第四種方式:原型鍊方式,即子類通過prototype将所有在父類中通過prototype追加的屬性和方法都追加到Child,進而實作了繼承 

  function Person(){ 

  Person.prototype.hello = "hello"; 

  Person.prototype.sayHello = function(){ 

    alert(this.hello); 

  function Child(){ 

  Child.prototype = new Person();//這行的作用是:将Parent中将所有通過prototype追加的屬性和方法都追加到Child,進而實作了繼承 

  Child.prototype.world = "world"; 

  Child.prototype.sayWorld = function(){ 

    alert(this.world); 

  var c = new Child(); 

  c.sayHello(); 

  c.sayWorld(); 

5、繼承的第五種方式:混合方式 

  混合了call方式、原型鍊方式 

  function Parent(hello){ 

    this.hello = hello; 

  Parent.prototype.sayHello = function(){ 

  function Child(hello,world){ 

    Parent.call(this,hello);//将父類的屬性繼承過來 

    this.world = world;//新增一些屬性 

  Child.prototype = new Parent();//将父類的方法繼承過來 

  Child.prototype.sayWorld = function(){//新增一些方法 

  var c = new Child("zhangsan","lisi"); 

  c.sayWorld();