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

Why are helper methods frequently used in Javascript? - Stack Overflow

programmeradmin2浏览0评论

New to Javascript, reading Crockford's Javascript: The Good Parts (among other things)

In the 4th chapter regarding functions Crockford is showing how to preserve this in the outer function for use in inner functions, which I understand.

My question is, in his example code and a ton more like it, why use this helper function:

myObject.double = function() {
  var that = this; 

  var helper = function () {
      that.value = add(that.value, that.value);
  }
  helper();
};

Is it maybe because add() is sitting out in global scope, while value is in myObject, so I need to copy this (myObject) then transfer to global where I can grab add()?

Otherwise I'm not sure why I need the helper function?

New to Javascript, reading Crockford's Javascript: The Good Parts (among other things)

In the 4th chapter regarding functions Crockford is showing how to preserve this in the outer function for use in inner functions, which I understand.

My question is, in his example code and a ton more like it, why use this helper function:

myObject.double = function() {
  var that = this; 

  var helper = function () {
      that.value = add(that.value, that.value);
  }
  helper();
};

Is it maybe because add() is sitting out in global scope, while value is in myObject, so I need to copy this (myObject) then transfer to global where I can grab add()?

Otherwise I'm not sure why I need the helper function?

Share Improve this question edited Mar 12, 2011 at 22:25 Robert Harvey 181k48 gold badges348 silver badges512 bronze badges asked Mar 12, 2011 at 22:22 Richard HollandRichard Holland 2,6832 gold badges23 silver badges35 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

In that section of the book he is demonstrating that it is conventional to use that when accessing the this object of a function's parent.

It is not necessary to use a helper function do do what the code does. It is just an example to illustrate how to get around scoping issues with the this object.

Encapsulation. The helper() in your example only exist in the scope of myObject.double() it won't be available / visible outside of it. I believe that it is called private method instead of "helper" function.

The book also says "this is bound to the wrong value". Is the "wrong" value of "this" the global object? The way Crockford fixes it makes me uncertain. Couldn't he have fixed it in a way more familiar to people with a "classic" background just by calling this.helper(), ie making helper() a public method? I would guess yes and guess that he did it the way he did it just to (also) show a workaround that still uses a function invokation pattern, but would like to have that confirmed; being new to javascript am not sure my guesses are correct.

发布评论

评论列表(0)

  1. 暂无评论