简体   繁体   English

关于此的JavaScript

[英]About this in javascript

I am confused about the way this behaves in some circumstances for example I have this code 我对某些情况下的行为感到困惑,例如我有这段代码

var makeRequest=function(url,callback){

  var data=10; 

  callback(data);
};

var obj = {
  someValue: 20,
  loadData: function(data){
    var sum = this.someValue + data;
    alert(sum);
  },
  prepareRequest:function(){
    var url="http://someurl.com";

    makeRequest(url,obj.loadData);

  }
};

It makes a request let s say and it gets some data. 让我们说一个请求,它获取了一些数据。 The thing is when I call the function makeRequest with obj.loadData as parameter it gives an error. 问题是,当我调用该函数makeRequestobj.loadData作为参数它给出了一个错误。 Can someone explain why it happens this? 有人可以解释为什么会这样吗? Why it doesn t behave the expected way when i call obj.prepareRequest() even tho the loadData method is attacked to obj object? 为什么当我调用obj.prepareRequest()即使loadData方法被攻击到obj对象,它也没有表现出预期的方式? I would appreciate any help. 我将不胜感激任何帮助。 "This" keyword is really confusing. “这个”关键字确实令人困惑。

At the point when you passed your loadData function as a parameter into makeRequest just think of switching ownership ... makeRequest now owns loadData so if there's any this keyword being used in loadData then it is referring to makeRequest not obj . 在当你通过你的点loadData函数作为参数到makeRequest只是觉得开关所有权... makeRequest 现在拥有 loadData所以如果有任何this在使用关键字loadData那么它指的是makeRequestobj

The way to maintain ownership or context is to use .bind() 维护所有权或上下文的方法是使用.bind()

loadData has no clue what this.someValue is because the context was changed loadData不知道this.someValue是什么,因为上下文已更改

In your prepareRequest function add bind and good practice is to use this for oop purposes 在您的prepareRequest函数中添加bind ,良好的做法是将this用于oop目的

Example

makeRequest(url,this.loadData.bind(this));

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM