jquery對外暴露了兩個方法:jQuery和$,
* 這兩方法實際上是同一個方法,
* 通過調用這兩個方法,可以得到一個jQuery執行個體對象。
* jQuery執行個體對象是一個僞數組對象。
* jQuery和$實際上是一個工廠函數。
先實作一個彈出框插件的實列:(為了實作插件機制,讓外界可以透過jQuery.fn擴充方法。)
<script>
/*
* jQuery插件實作機制:
* 就是給原型添加一些功能方法。
* */
(function( w ) {
// 對外暴露的工廠函數
function jQuery() {
return new jQuery.fn.init();
}
// 給原型提供一個簡寫方式
jQuery.fn = jQuery.prototype = {
};
// init是jQuery中真正的構造函數
var init = jQuery.fn.init = function() {
};
// 替換構造函數的原型 為 jQuery工廠的原型
init.prototype = jQuery.fn;
// 把工廠通過兩個變量暴露出去
w.jQuery = w.$ = jQuery;
}( window ));
// 實作一個jQ彈出框插件
jQuery.fn.alert = function( msg ) {
alert( msg );
};
// 測試插件
var $$ = $();
$$.alert('彈出框插件');
</script>
Object.prototype.toString:
作用:根據内部的this傳回一個類似于這樣的字元串'[object constructorName]'
這個方法有個缺點,不能擷取使用者自定義對象的具體類型,隻能擷取内置對象的類型。
//測試
console.log(Object.prototype.toString.call([]));
console.log(Object.prototype.toString.call( new Date() ));
console.log(Object.prototype.toString.call( Array ));
console.log(Object.prototype.toString.call( Date ));
簡寫 ==> 因為{}對象直接繼承Object.prototype,
是以通過這個對象得到的toString,一定來自Object.prototype。
console.log(({}).toString.call([]));
console.log(({}).toString.call( new Date() ));
console.log(({}).toString.call( Array ));
console.log(({}).toString.call( Date ));
用這個toString擷取自定義對象的類型
function Person(){}
var xiaofang = new Person();
console.log(({}).toString.call( xiaofang ));
代碼塊就是一對大括号。
{
var a = 1;
console.log(a);
}
{}.toString();//錯誤
console.log(({}).toString());