如不雅在严格模式下把一个办法作为函数来调用,this为undefined。 同时会获得一个警告:
- var counter = {
- count: 0,
- // Strict-mode method
- inc: function () {
- 'use strict';
- this.count++;
- }
- }
- callIt(counter.inc);
- // TypeError: Cannot read property 'count' of undefined
- console.log(counter.count);
- 修改办法是应用bind():
- var counter = {
- count: 0,
- inc: function () {
- this.count++;
- }
- }
- callIt(counter.inc.bind(counter));
- // 成功了!
- console.log(counter.count); // 1
bind()创建了一个新的函数,它老是能获得一个指向counter的this。
当在一个办法中应用通俗函数时,很轻易忘记前者具有其本身this(即使其不须要this)。 是以,你不克不及早年者引用该办法的this,因为该this会被掩蔽。 让我们看看竽暌箍现问题的例子:
- var obj = {
- name: 'Jane',
- friends: [ 'Tarzan', 'Cheeta' ],
- loop:
推荐阅读
有奖调研 | 人脸辨认功能在互联网行业认知度情况经由过程应用法度榜样级其余感知和洞察,为微办事带来编排和主动化的优势 微软的 Azure Service Fabric 的官方博客在2017.3.2>>>详细阅读
本文标题:JavaScript中this的运行机制及爬坑指南
地址:http://www.17bianji.com/lsqh/40750.html
1/2 1