先来这段奇怪代码:
function Person() { Person.say() } Person.say = function () { console.log("hello"); } console.log(Person.say.prototype); console.log(Person.prototype); console.log(Person.say.prototype === Person.prototype); console.log(Person.say.constructor); console.log(Person.constructor); console.log(Person.say.constructor === Person.constructor); console.log(Person.say.__proto__); console.log(Person.__proto__); console.log(Person.say.__proto__ ===Person.__proto__);
jQuery里面有用到类试代码,本人也不太明白,只能从打印结果略知一点。先记住可以这么用,有大神看到的话麻烦告知在下,现在这里多谢了。
下面一步是有关原型的,先要了解这部的意思,最少要能读懂。
(function( w ) { // 工厂 function jQuery( selector ) { return new jQuery.fn.init( selector ); }; //原型简称以及替换原型 jQuery.fn = jQuery.prototype = { constructor: jQuery }; // 这是真正的构造函数,同时把构造函数放在了原型中 var init = jQuery.fn.init = function( selector ) {}; // 判断是不是函数 这里来一句刚开始时使用到的代码 init.isFunction = function( fn ) { if ( typeof fn === 'function' ) { return true; } return false; }; // 替换init的原型为工厂的原型,这样外界就可以通过工厂给实例扩展方法 init.prototype = jQuery.fn; // 暴露工厂和工厂的简称 w.jQuery = w.$ = jQuery; }( window )); // 在外界实例可以通过constructor得到工厂,通过init得到构造函数 console.log($().constructor); console.log($().init);
原型简称那里也用到了刚开始的代码,先记录这,等我哪天明白了在来说明。
function Person() { Person.say() } Person.say = function () { console.log(this); } Person();从输出结果知道,this指向Person函数,在之后的封装中会用到这个。