<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-3.1.0.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
通過$符號調(diào)用的函數(shù)稱作工具函數(shù),要給工具函數(shù)添加新插件竖独,需要通$.extend()方法
使用extend給jq擴(kuò)展新功能糙俗,參數(shù)類型是一個對象,屬性名就是新方法的名字预鬓,屬性的值就是新方法的功能函數(shù)
下面代碼中巧骚,通過$.extend()向jQuery添加了一個sayHello函數(shù),然后通過$直接調(diào)用格二。
$.extend({
sayHello:function(name){
console.log('hello'+name)
}
});
$.sayHello();
$.extend({
sayHello:function(name){
console.log('hello'+(name ? name:'葛二蛋'));
}
});
$.sayHello('媛兒');
比如一個自定義的console劈彪,輸出特定格式的信息,定義一次后可以通過jQuery在程序中任何需要的地方調(diào)用它顶猜。
$.extend({
log: function(message) {
//獲取當(dāng)前的年月日沧奴、時分秒
var now = new Date,
y = now.getFullYear(),
m = now.getMonth() + 1,
d = now.getDate(),
h = now.getHours(),
mi = now.getMinutes(),
s = now.getSeconds();
var time = y + '/' + m + '/' + d + '' + h + ':' + mi + ':' + s;
console.log(time + message);
}
});
$.log("老師你是痘痘嗎")
var obj1 = {
name: '老漢',
age: 88
}
var obj2 = {
name: '推車',
size: 100
}
var obj = $.extend(obj1, obj2);
console.log(obj);
console.log(obj1);
使用extend()方法合并多個對象,會把多個對象的屬性合并對象里长窄,并返回滔吠,如果屬性值同名纲菌,則屬性值是最后一個屬性值
</script>
</head>
<body>
</body>
</html>