栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

js函数和this用法实例分析

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

更多关于Javascript相关内容可查看本站专题:《Javascript常用函数技巧汇总》、《javascript面向对象入门教程》、《Javascript错误与调试技巧总结》、《Javascript数据结构与算法技巧总结》及《Javascript数学运算用法总结》

希望本文所述对大家Javascript程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/70958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号