六 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优先级别是最高的

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值