ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 对象内“this”的范围

2019-05-19 12:26:07  阅读:92  来源: 互联网

标签:javascript


这(下面)最终给了我“超出最大调用堆栈大小”的错误.看起来这是由于“this.actions”对象中“this”的解释方式.在该对象中,“this”是指那个对象,还是Unit类的实例?如果是前者,将.bind(this)放在“this.actions”对象的末尾,使“this”引用类实例代替?如果是这样,为什么?如果没有,为什么不呢?

function Unit(){
  this.move = function(direction){
    switch(direction){
      case 'up': { console.log('foo'); break; }
      case 'down': { console.log('foooo'); break; }
    }
    console.log('bar');
  }
  this.shoot = function(){console.log('zap')}

  this.actions = {
    'moveUp' : function(){ this.move('up') },
    'moveDown' : function(){ this.move('down') },
    'shoot' : function(){ this.shoot() }
  }

  return this
}

解决方法:

actions对象中的关键字this将引用actions对象.

一些可能的修复可能如下所示:

function Unit(){
  var self = this;
  this.move = function(direction){
    switch(direction){
      case 'up': { console.log('foo'); break; }
      case 'down': { console.log('foooo'); break; }
    }
    console.log('bar');
  }
  this.shoot = function(){console.log('zap')}

  this.actions = {
    'moveUp' : function(){ this.move('up') }.bind(self),
    'moveDown' : function(){ this.move('down') }.bind(self),
    'shoot' : function(){ this.shoot() }.bind(self)
  }

  return this
}

或者,当您调用这些方法时,可以使用call或apply

例如:

var coolUnit = new Unit();
Unit.actions.moveUp.call(coolUnit);

在对象的上下文中理解这一点需要一些工作,但这里有一些资源:

How does the “this” keyword work?

http://unschooled.org/2012/03/understanding-javascript-this/

http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

TL; DR – 您可以使用一系列心理“规则”来帮助跟踪在给定上下文中的内容.例如.左点的规则,其中“点”左侧的对象获得此绑定.

Object.foo() <- `this` in the method `foo` will point to `Object`

使用上面提到的“规则”,您可以合理化新的Unit.actions.moveUp()将此绑定设置为指向actions对象,因为它的左侧为点.

或者您可以使用call / bind / apply将其绑定到您希望的上下文,如上所示.

标签:javascript
来源: https://codeday.me/bug/20190519/1134898.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有