js函數(shù)和this用法實例分析
本文實例講述了js函數(shù)和this用法。分享給大家供大家參考,具體如下:
js的所有代碼都是由funtion組成,funtion即函數(shù)的類型。
一.函數(shù)有兩種寫法
-----1.定義式
function test() { //定義一個函數(shù)
console.log("function test called!!");
}
-----2.變量式
var test2 = function () {
console.log("var test2 function called!!");
};
我們可以調(diào)用typeof()查看類型
var type = typeof(test2); console.log(type); //function
二.函數(shù)也是對象
-----1.函數(shù)既然是對象,即就可以有屬性和功能。函數(shù)也可以動態(tài)的增加屬性,如下:
function test() {
console.log("function test() called!!!");
}
test.user_name = "zhangsan";
console.log(test.user_name); //zhangsan
三.函數(shù)的實例化
函數(shù)的實例化也有兩種方式:
---------1.直接在函數(shù)名后面加上"()" @@@@@常用這種方式
function test() {
console.log("function test() called!!!");
}
test(); //function test() called!!!
---------2.使用關(guān)鍵字"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-----------
//函數(shù)名.call(this,參數(shù)...) 顯示傳遞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)先級最高
//函數(shù).bind,不會改變原來函數(shù)對象的this,而是會產(chǎn)生一個新的臨時的對象
//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的時候,
//不是由調(diào)用者來決定的
new_func.call({ 0: 1 }, 3, 4); //this還是表{name:"jade"},不是{0:1}
//==================總結(jié)=============================
//在函數(shù)里面訪問this,this是由調(diào)用的環(huán)境來決定的,不確定,一般不使用
//1.顯示的傳遞this,函數(shù).call(this對象,參數(shù))
//2.隱式的傳遞this,表.key_函數(shù)(參數(shù)),this---》表
//3.bind優(yōu)先級別是最高的
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《JavaScript常用函數(shù)技巧匯總》、《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
- 改變javascript函數(shù)內(nèi)部this指針指向的三種方法
- JS函數(shù)this的用法實例分析
- 詳解JS構(gòu)造函數(shù)中this和return
- JavaScript函數(shù)中的this四種綁定形式
- JavaScript 嵌套函數(shù)指向this對象錯誤的解決方法
- 深入理解Javascript箭頭函數(shù)中的this
- js對象內(nèi)部訪問this修飾的成員函數(shù)示例
- 深入理解js函數(shù)的作用域與this指向
- JS匿名函數(shù)內(nèi)部this指向問題詳析
- 淺談Javascript中的函數(shù)、this以及原型
- JavaScript箭頭函數(shù)中的this詳解
相關(guān)文章
javascript通過class來獲取元素實現(xiàn)代碼
javascript獲取元素有很多的方法,本文簡單的介紹下通過class獲取元素的實現(xiàn)代碼,感興趣的朋友可以參考下,希望本文知識點可以幫助到你2013-02-02

