<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>函数</title>
</head>
<body>
<button>发送短信1</button>
<button>发送短信2</button>
<button>发送短信3</button>
<script>
// 1-创建函数方式
// 01 自定义函数
function fn(){}
// 02 函数体方式
var fn=function(){}
// 03 创建对象方式
// 所有函数都是Function的实例
var fn=new Function('a','b','console.log(a+b)');
fn(1,5); //调用
console.dir(fn);
console.log(fn.__proto__===Function.prototype);
// 所有的函数都是Function的实例 对象
console.log(fn instanceof Object);
// 2-函数的调用
//01普通函数调用 fn() fn.call(o)
//02 对象函数 ldh.sayHi();
//03 构造函数 new Star()
//04 绑定事件函数 btn.onclick=function(){}
//05 定时器函数 setIterval(function(){},1000);
//06 立即执行函数 (function(){console.log("立即执行,到达人生巅峰!")})()
// (function(){console.log("立即执行,到达人生巅峰!")})()
// 3-this指向问题 一般情况下指向函数调用者
//01普通函数调用
// fn() this指向window
// fn.call(o) this指向对象o
//02 对象函数 ldh.sayHi(); this指向实例对象ldh
//03 构造函数 new Star() 指向实力对象 eg:zxy=new Star(""张学友) this指向zxy
//04 绑定事件函数 btn.onclick=function(){} this指向btn 指向函数调用者
//05 定时器函数 setIterval(function(){},1000); this指向window
//06 立即执行函数 (function(){console.log("立即执行,到达人生巅峰!")})() this指向window
// 4-改变this指向
// 01 call方法 call调用函数 改变this指向 实现继承
let o = {
name:'lhm',
age:18
}
function fn2(x,y){
console.log(this);
console.log(this.name+'----'+this.age);
console.log(x+y);
}
fn2.call(o,3,4);
function Father(name,age){
this.name=name;
this.age=age;
}
Father.prototype.sing=function(){
console.log(this.name+'会唱歌!')
}
function Son(name,age){
// 实现继承
Father.call(this,name,age);
}
// 继承父亲prototype方法
Son.prototype=new Father;
Son.prototype.constructor=Son;
let son=new Son("刘德华",60);
console.log(son.name+'--'+son.age);
son.sing();
// 02 apply方法 跟call方法一样 要求第二个参数是一个数组
console.log("apply方法");
let arr=[6,8,9] //传多了就接收前面的
fn2.apply(o,arr);
// apply内置应用
let max=Math.max.apply(Math,arr);
console.log(max);
// 03 bind方法 bind捆绑 改变this指向 跟call一样,但是call可以调用函数 bind不可以调用函数
let a=fn2.bind(o,7,8); //不调用 但是返回一个新函数,a就是改变this指向产生的新函数
console.log("bind方法:");
a();
// bind方法应用 实际开发用的最多
// 有的函数不想立即调用,但是又想改变this指向
// 发送短信案例 点击之后禁用3s才能点击 让定时器自己调用
var btns=document.querySelectorAll("button");
btns.forEach((item,index)=>{
item.onclick=function(){
this.disabled=true;
// bind不会立即调用 让setTimeout调用 但成功改变this指向
setTimeout(function(){
this.disabled=false;
}.bind(this),3000)
}
})
// // call apply bind总结
// call apply 基本一样,call经常做继承 apply传参必须是数组,经常跟数组相关
// bind不会调用函数 fn.bind()不调用 跟定时器经常相关
</script>
</body>
</html>
js--function recognition
Guess you like
Origin blog.csdn.net/enhenglhm/article/details/123901219
Recommended
Ranking