js函数和this用法实例分析
网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要介绍了js函数和this用法,结合实例形式分析了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.函数既然是对象,即就可以有属性和功能。函数也可以动态的增加属性,如下:
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,优先级最高 //函数.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有什么区别呢?== //bind最牛的地方是什么?是绑定this的时候, //不是由调用者来决定的 new_func.call({ 0: 1 }, 3, 4); //this还是表{name:"jade"},不是{0:1} //==================总结============================= //在函数里面访问this,this是由调用的环境来决定的,不确定,一般不使用 //1.显示的传递this,函数.call(this对象,参数) //2.隐式的传递this,表.key_函数(参数),this---》表 //3.bind优先级别是最高的
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:测试上述代码运行效果。
更多关于JavaScript相关内容可查看本站专题:《》、《》、《》、《》及《》
希望本文所述对大家JavaScript程序设计有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程