一般情况下实例化的过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <script type= "text/javascript" > //创建一个构造函数 function Person(name, sex){ this .name = name; this .sex = sex; } //创建构造函数的原型对象 Person.prototype={ constructor:Person, eat: function (){ console.log( this .name + "吃了一个大鸡腿!" ); } } //调用构造函数必须要使用new var per = new Person( "LeoKim" , "男" ); per.eat(); </script> |
Jquery的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <script type= "text/javascript" > function Person(name, sex){ return new per(name, sex); } function per(name, sex){ this .name = name; this .sex = sex; } Person.prototype={ constructor:Person, eat: function (){ console.log( this .name + "吃了一只老公鸡!" ) } } //js引擎会在per中查找eat方法,如果没找到就会到per的原型链上去找,所以这里需要把per的原型链复制为Person的原型链 per.prototype = Person.prototype; var p = Person( "LeoKim" , "男" ); p.eat(); </script> |
jQuery 的方式是通过原型传递解决问题,把 jQuery 的原型传递给jQuery.prototype.init.prototype
所以通过这个方法生成的实例 this 所指向的仍然是 jQuery.fn,所以能正确访问 jQuery 类原型上的属性与方法