js函數和this用法實例分析
本文實例講述了js函數和this用法。分享給大家供大家參考,具體如下:
js的所有代碼都是由funtion組成,funtion即函數的類型。
一.函數有兩種寫法
-----1.定義式
function test() { //定義一個函數
console.log("function test called!!");
}
-----2.變量式
var test2 = function () {
console.log("var test2 function called!!");
};
我們可以調用typeof()查看類型
var type = typeof(test2); console.log(type); //function
二.函數也是對象
-----1.函數既然是對象,即就可以有屬性和功能。函數也可以動態(tài)的增加屬性,如下:
function test() {
console.log("function test() called!!!");
}
test.user_name = "zhangsan";
console.log(test.user_name); //zhangsan
三.函數的實例化
函數的實例化也有兩種方式:
---------1.直接在函數名后面加上"()" @@@@@常用這種方式
function test() {
console.log("function test() called!!!");
}
test(); //function test() called!!!
---------2.使用關鍵字"new"進行實例化
function test() {
console.log("function test() called!!!");
}
new test(); //function test() called!!!
四.this機制
//=====================this機制==================
function my_func(rhs, lhs) {
console.log(this, rhs, lhs);
}
//顯示不確定的this
//my_func(); //console顯示
//--------------顯示傳遞this-----------
//函數名.call(this,參數...) 顯示傳遞this
my_func.call({ 0: "jade" }, 2, 3);
//------------------------------------
var tools = {
my_func: my_func,
};
//表.key() --->this是表
tools.my_func(2, 3); //this是tools
// 相當于
tools.my_func.call(tools, 2, 3);
//強制綁定this,優(yōu)先級最高
//函數.bind,不會改變原來函數對象的this,而是會產生一個新的臨時的對象
//bind好了this
var new_func = my_func.bind({ name: "jade" });
new_func(3, 4);
tools.my_func = new_func;
tools.my_func(3, 4); //this是表{name:"jade"}
my_func(3, 4); //this不變,consloe
//====call與bind有什么區(qū)別呢?==
//bind最牛的地方是什么?是綁定this的時候,
//不是由調用者來決定的
new_func.call({ 0: 1 }, 3, 4); //this還是表{name:"jade"},不是{0:1}
//==================總結=============================
//在函數里面訪問this,this是由調用的環(huán)境來決定的,不確定,一般不使用
//1.顯示的傳遞this,函數.call(this對象,參數)
//2.隱式的傳遞this,表.key_函數(參數),this---》表
//3.bind優(yōu)先級別是最高的
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關于JavaScript相關內容可查看本站專題:《JavaScript常用函數技巧匯總》、《javascript面向對象入門教程》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。

