简体   繁体   English

对象文本模式回调这种混乱

[英]Object literal pattern callback and this confusion

var App = {
  method : function (value, callback) {
    console.log(value);  
    if (typeof callback === 'function') {
      //here
      callback.call( this );
    } 
  } 
} 

App.method('Hey there', function(){
  console.log('callback was executed!');
}); 

Why do I can't do callback(), but have to call(this) for the callback? 为什么我不能执行callback(),但必须调用(this)进行回调?

To put it simply, you don't have to. 简单地说,您不必这样做。 Unless you want your callback function to have its context be the "App" object. 除非你想你的回调函数有其背景是“应用程序”对象。 For example: 例如:

 // Regular callback: var App = { method : function (value, callback) { if (typeof callback === 'function') { callback(); } } } App.method('Hey there', function(){ console.log( 'A regular callback was executed!', 'And its context is Window:', this === window ); }); // Context modified callback: var App = { method : function (value, callback) { if (typeof callback === 'function') { callback.call( this ); } } } App.method('Hey there', function(){ console.log( 'A context modified callback was executed!', 'And its context is App:', this === App ); }); 

I hope that helps! 希望对您有所帮助!

In the specific case of the callback function you're supplying, it would not matter if you invoked the callback simply with: 在您提供的回调函数的特定情况下,仅用以下命令调用回调就没关系:

   callback();

Your callback code does not refer to this at all, so it makes no difference what value it has. 您的回调代码完全没有引用this ,因此它的值没有区别。

If, however, the callback wanted to refer to other parts of the App object, then invoking with callback.call(this) would ensure that this refers to App in the callback. 然而,如果回调要参考其他地区的App对象,然后用调用callback.call(this)将确保this指的是App的回调。 Example: 例:

var App = {
  method : function (value, callback) {
    console.log(value);  
    if (typeof callback === 'function') {
      //here
      callback.call( this );
    } 
  },
  property: "HELLO WORLD"
} 

App.method('Hey there', function(){
  console.log('callback was executed! Property value is: ' + this.property);
}); 

With that code, this would have to refer to App in order for the console.log() call to access the object property. 与该代码, this都将不得不提及到App ,以使console.log()调用访问对象的属性。 The use of .call() ensures that. .call()的使用确保了这一点。

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

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