Javascript - 函数分类 & this指向

Javascript中定义函数的三种方式,通过实例来说明吧。
<script>//method1function fn() {console.log('fn created ');}//method2var fn2 = function () {console.log('fn2 created');}//method3var fn3 = new Function('test', 'console.log(test);');fn3('fn3 test');console.dir(fn3);console.log(fn3 instanceof Object);</script>
运行上面例子,证明了函数也是对象。可以采用new + 构造函数的方式创建实例,第三种方式执行效率低。
函数的原型链

从结果可以看到Function原型对象的__proto__指向Object。

js中函数的分类和调用方式。
通过实例来说明吧。
<script>//函数的分类和调用方式//方式1 普通标准函数,this 指向windowfunction fn() {console.log('fn1'+ this);}fn(); //本质是window.fn(); 全局函数是window的成员//方式2 对象的方法 this 指向调用者ovar o = {sayHi: function () {console.log('fn2'+this);}}o.sayHi();//方式3 构造函数 this指向新创建的对象,这里指向star1function Star(username){this.username = username;}var star1 = new Star('ldh');//方式4 绑定事件函数 this 指向函数的调用者 btnvar fn = function (){console.log('btn 被点击了'+ this);}btn.onclick = fn;//点击了按钮就可以调用函数//方式5 定时器函数 定时器实际是window成员 所以this 就是windowsetInterval(function(){},1000);//定时器按照设定的时间间隔去调用//方式6 立即执行函数 this 是window 同方式一(function(){console.log('function executed')})();//不需要调用立即执行</script>
通过上面的例子,基本上归纳了笔者了解的函数使用方式。通过方式4和方式6的对比,
我们可以知道函数后面加了() 表示立即调用,没加(),表示函数的指针,只是指明函数不调用函数。
this 指向问题,牢记this指向调用者
改变this 指向的三个函数
this 指向是JS中很重要的问题,在上面的函数分类中,已经有了系统的分析。下面重点总结改变this 指向的三个函数。
call
把父类实例改成子类实例 实现属性继承。
<script>//call functionfunction Father(username, age) {this.username = username;this.age = age;}function Son(username, age, gender) {Father.call(this, username, age);//实现继承父类的属性this.gender = gender;}</script>
apply
apply 和call 不同点,参数是数组(伪数组)。在apply内部会把数组拆成元素
主要使用 借助Math对象,Math.max.apply(Math, [4324, 45, 342, 23])
<script>//apply functionvar o = {username: 'testuser'};function fn(arr) {console.log(arr);for (let i = 0; i < arr.length; i++) {console.log(arr[i]);}console.log(this);}fn.apply(o, [23, 43]);console.log(Math.max(43, 45, 243, 342));console.log(Math.max.apply(Math, [4324, 45, 342, 23]));</script>
bind
只改变this 的指向 不调用函数。
用途改变绑定事件的this,案例:
<body><button>click me</button><button>click me</button><button>click me</button><script>//bind function//案例:实现多个按钮发送验证码后 3s 可以再次发送var btns = document.querySelectorAll('button');for (let i = 0; i < btns.length; i++) {btns[i].onclick = function () {this.disabled = true;setTimeout(function () {this.disabled = false;//改变this 指向btn ,3000ms 后执行}.bind(this), 3000);}}</script></body>
本文完~
学习更多技能
请点击下方公众号
![]()

评论
