说一下好处:这个封装函数可以可以实现子类继承父类原型对象里面的所有方法和属性,但是也留了第二条路,去继承父类构造函数的里面的东西。
两个参数分别是子类的构造函数,后面是父类构造函数
$.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> |
jquery的优良继承方法
原文地址:http://www.cnblogs.com/guangixn/p/7895264.html