jquery的優良繼承方法


說一下好處:這個封裝函數可以可以實現子類繼承父類原型對象里面的所有方法和屬性,但是也留了第二條路,去繼承父類構造函數的里面的東西。

兩個參數分別是子類的構造函數,后面是父類構造函數

 


$.inherits = function(childCtor, parentCtor) {
定以一個第三方構造函數
function tempCtor() {};
把父類的原型方法賦給第三方構造函數的原型對象
tempCtor.prototype = parentCtor.prototype;
這條的意思是先讓子的構造函數,繼承父構造函數的原型對象()
childCtor.superClass_ = parentCtor.prototype;,
子構造函數繼承第三方構造函數的原型對象(跟上邊一樣,但是引用改變了)
childCtor.prototype = new tempCtor();
// childCtor.prototype.constructor = childCtor;
}

 

 

  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  </head>
  <body>
   
  </body>
   
  <script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
  <script src="./extend.js"></script>
  <script>
   
   
   
  function Parent(){
  this.word = "hello"
  }
   
  // Parent.prototype = {
  // sayHello: function() {
  // alert(this.word)
  // }
  // }
  $.extend(Parent.prototype,{
  sayHello: function() {
  alert(this.word)
  }
  })
   
   
  function Child() {
  Parent.call(this)
  }
   
  // Child.prototype = {
  // sayHello: function() {
  // this.superClass_.sayHello();
  // alert("world");
  // }
  // }
  $.inherits(Child, Parent);
   
  $.extend(Child.prototype,{
  sayHello: function() {
  Child.superClass_.sayHello.call(this);
  alert("world");
  }
  })
   
   
   
  var child = new Child()
  child.sayHello();
   
  </script>
  </html>


免責聲明!

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



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