欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js函數(shù)和this用法實(shí)例分析

 更新時(shí)間:2020年03月13日 12:58:08   作者:jadeshu  
這篇文章主要介紹了js函數(shù)和this用法,結(jié)合實(shí)例形式分析了js函數(shù)和this基本功能、原理、使用方法與操作注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了js函數(shù)和this用法。分享給大家供大家參考,具體如下:

js的所有代碼都是由funtion組成,funtion即函數(shù)的類型。

一.函數(shù)有兩種寫法

-----1.定義式

function test() { //定義一個(gè)函數(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ù)也是對(duì)象

-----1.函數(shù)既然是對(duì)象,即就可以有屬性和功能。函數(shù)也可以動(dòng)態(tài)的增加屬性,如下:

function test() {
    console.log("function test() called!!!");
}
test.user_name = "zhangsan";
console.log(test.user_name); //zhangsan

三.函數(shù)的實(shí)例化

    函數(shù)的實(shí)例化也有兩種方式:

---------1.直接在函數(shù)名后面加上"()"         @@@@@常用這種方式

function test() {
    console.log("function test() called!!!");
}
test(); //function test() called!!!

---------2.使用關(guān)鍵字"new"進(jìn)行實(shí)例化

function test() {
    console.log("function test() called!!!");
}
new test(); //function test() called!!!

四.this機(jī)制

//=====================this機(jī)制==================
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
// 相當(dāng)于
tools.my_func.call(tools, 2, 3);
 
//強(qiáng)制綁定this,優(yōu)先級(jí)最高
//函數(shù).bind,不會(huì)改變?cè)瓉砗瘮?shù)對(duì)象的this,而是會(huì)產(chǎn)生一個(gè)新的臨時(shí)的對(duì)象
//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的時(shí)候,
//不是由調(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對(duì)象,參數(shù))
//2.隱式的傳遞this,表.key_函數(shù)(參數(shù)),this---》表
//3.bind優(yōu)先級(jí)別是最高的

感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.jb51.net/code/HtmlJsRun測試上述代碼運(yùn)行效果。

更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《JavaScript常用函數(shù)技巧匯總》、《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)

希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論