說一下好處:這個封裝函數可以可以實現子類繼承父類原型對象里面的所有方法和屬性,但是也留了第二條路,去繼承父類構造函數的里面的東西。
兩個參數分別是子類的構造函數,后面是父類構造函數
$.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> |
