标签:function ES6 console 进阶 Day03 bind 函数 var log
函数定义方法
//自定义函数,又称命名函数
function one(){
console.log("第一种定义方法");
}
one();
//函数表达式,又称匿名函数
var two = function(){
console.log("第二种定义方法");
}
two();
//利用new function()
var three = new Function('a','b','console.log("第三种定义方法");console.log(a+b)')
three(1,2);
//查看__proto__
console.dir(three);
console.log(three instanceof Object);
注意
- 第三种方法执行效率低,不怎么使用
- 所有的函数都是function的实例对象
- 函数也是对象
函数调用,6种方法
//1.普通函数
function one(){
console.log("普通函数");
}
one();
one.call();
//2.对象的方法
var two = {
say:function(){
console.log("对象的方法 say");
}
}
two.say();
// 3.构造函数
function Three(){
console.log("构造函数");
}
new Three();
// 4.绑定事件函数
var four = document.querySelector("button");
four.onclick = function(){
console.log("绑定事件");
}
// 5.定时器函数
var five = setInterval(function(){
console.log("定时器函数");
},1000)
clearInterval(five);
// 6.立即执行函数
var six = (function(){
console.log("立即执行函数");
})()
this指向问题
//1.普通函数
//this指向window
function one(){
console.log("普通函数");
}
one();
one.call();
//2.对象的方法
//this指向调用它的对象 two
var two = {
say:function(){
console.log("对象的方法 say");
}
}
two.say();
// 3.构造函数
//指向实例对象 ldh
//原型对象里面的this指向也是实例对象 ldh
function Three(){
console.log("构造函数");
}
var ldh = new Three();
// 4.绑定事件函数
//this指向绑定者,four
var four = document.querySelector("button");
four.onclick = function(){
console.log("绑定事件");
console.log(this);
}
// 5.定时器函数
//this指向绑定者,five;也可以指向window
var five = setInterval(function(){
console.log("定时器函数");
},1000)
clearInterval(five);
// 6.立即执行函数
//此刻this指向window
(function(){
console.log("立即执行函数");
})()
改变this指向的方法
<button>bind</button>
<script>
// 1.call() 既可以调用函数,又可以改变函数内的this,主要作用靠继承
//2.bind() 不回调用函数,可以改变this指向 使用较多
//返回的是原函数改变this的新函数
var bind={
name:"andy"
}
function dnib(){
console.log(this)
}
var b = dnib.bind(bind);
b();
//举例,当有些函数不需要立即调用,但是又需要改变内部this指向,就可以使用bind()
var btn = document.querySelector('button');
btn.onclick = function(){
this.disabled = true;
// 不使用bind
// var that = this;
// setInterval(function(){
// that.disabled = false;
// },3000)
// 使用bind
var that = this;
setInterval(function(){
this.disabled = false;
}.bind(this),3000)//这里的this指向的btn这个对象
}
</script>
区别
- call()和apply()相似,但是传参不一样;
- call()传递参数arg1、arg2,而apply()必须以数组形式;
- bind()不会直接调用函数;
- call做继承,apply用在数组类函数,bind用在不调用但是需要改变this指向。
高阶函数
标签:function,ES6,console,进阶,Day03,bind,函数,var,log 来源: https://blog.csdn.net/weiweianx/article/details/114005452
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。