最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is my understanding of the `callback` keyword correct here? - Stack Overflow

programmeradmin2浏览0评论

The following code snippet is part of an exercise in which I need to guess the output of the code:

let length = 4;
function callback(){
  console.log(this.length);
}
const object = {
  length: 5,
  method(callback){
    callback();
  },
};
object.method(callback, 1, 2);

The following code snippet is part of an exercise in which I need to guess the output of the code:

let length = 4;
function callback(){
  console.log(this.length);
}
const object = {
  length: 5,
  method(callback){
    callback();
  },
};
object.method(callback, 1, 2);

From what I understood so far, the following is the process going on behind the scenes:

From the current understanding:

--> line 11: callback definition is passed as arg.

--> line 7: callback definition is used as input for param.

--> line 8: callback keyword is called.

--> line 11: callback() defined on line 2 is executed as a function with global scope.

--> line 3: this.length refers to window.length and output = 0 is obtained.

--> And the args 1 and 2 are irrelevant.

Please help me verify if the above explanation is correct or not. Thank you!

Share Improve this question asked yesterday SteveSteve 452 silver badges6 bronze badges 1
  • 5 "callback" is not a keyword in JavaScript. It's an identifier. And what's being passed is a reference to the callback() function, not its "definition". – Pointy Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 1

It looks like the issue here is this related.

In non-strict mode, this inside callback() points to the global window object, making this.length equal to window.length, which is usually 0.

When you call callback() directly inside method, you’re not invoking it as a method of any object. In non-strict mode, a standalone function call defaults this to the global object → window.

The global let length = 4; does not define length as a property on window, it simply declares a block-scoped variable in the global scope. Therefore, it does not affect this.length.

The extra arguments (1, 2) are ignored because method only takes one parameter (callback) and does nothing with those arguments.

EDIT 1 :

window.length represents the number of frames (sub-browsing contexts). As you don’t have any iframes, window.length is 0. So the log statement ends up printing 0.

Example of working code :

function callback() {
  console.log(this.length);
}

const object = {
  length: 5,
  method(cb) {
    // Force 'this' to be 'object'
    cb.call(this);
  },
};

object.method(callback, 1, 2);

发布评论

评论列表(0)

  1. 暂无评论