开发者

'this' object can't be accessed in private JavaScript functions without a hack?

I was working on a project for a while, trying to figure out开发者_如何学Python what I was doing wrong, when I finally narrowed "the bug" down to the fact that the below code doesn't work as I expected:

function Alpha()
    {
    this.onion = 'onion';

    function Beta()
        {
        alert(this.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'undefined'

However, if I change the code to this:

function Alpha()
    {
    var self = this;
    this.onion = 'onion';

    function Beta()
        {
        alert(self.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'onion'

it works like I would expect. After wasting a large portion of my life, can anyone explain why it works like this?


Works like this because each function has associated its own execution context.

However there are other ways to do it, for example:

Using call or apply to invoke the function:

function Alpha() {
  this.onion = 'onion';

  function Beta() {
    alert(this.onion);
  }

  Beta.call(this);
}

var alpha1 = new Alpha();
// Alerts 'onion'

The new ECMAScript 5th Edition Standard, introduces a way to persist the function context, the Function.prototype.bind method:

function Alpha() {
  this.onion = 'onion';

  var Beta = function () {
    alert(this.onion);
  }.bind(this);

  Beta();
}

var alpha1 = new Alpha();
// Alerts 'onion'

We can say that the Beta function is bound, and no matter how you invoke it, its this value will be the intact.

This method is not widely supported yet, currently only IE9pre3 includes it, but you can include an implementation to make it work now.

Now let me elaborate about how this works:

The this value exist on each execution context, and for Function Code is set implicitly when a function call is made, the value is determined depending how the reference if formed.

In your example, when you invoke Beta();, since it is not bound to any object, we can say that the reference has no base object, then, the this value will refer to the global object.

Other case happens when you invoke a function that is bound as a property of an object, for example:

var obj = {
  foo: function () { return this === obj;}
};
obj.foo(); // true

As you can see, the reference being invoked obj.bar(); contains a base object, which is obj, and the this value inside the invoked function will refer to it.

Note: The reference type is an abstract concept, defined for language implementation purposes you can see the details in the spec.

A third case where the this value is set implicitly is when you use the new operator, it will refer to a newly created object that inherits from its constructor's prototype:

function Foo () {
  return this; // `this` is implicitly returned when a function is called 
}              // with `new`, this line is included only to make it obvious

var foo = new Foo();
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true


From JavaScript: The Definitive Guide, 5th Edition (the rhino book):

When a function is invoked as a function rather than as a method, the this keyword refers to the global object. Confusingly, this is true even when a nested function is invoked (as a function) within a containing method that was invoked as a method: the this keyword has one value in the containing function but (counterintuitively) refers to the global object within the body of the nested function.

Note that this is a keyword, not a variable or property name. JavaScript syntax does not allow you to assign a value to this.

Two things to pay attention to here:

  1. this isn't a variable, so the normal closure capture rules don't apply.
  2. this is "rebound" on every functiion calls, whether as a method, a normal function call, or via new. Since you're doing a normal function call (when calling Beta), this is getting bound to the "global object".


When you call a non-member function (not called as someObject.method()), it runs in the context of the window. It doesn't matter whether it's a private function or a global one.

You could do:

Beta.call(this);

call allows you to call a function while passing a context as the first argument (apply is similar, but the argument list is an array).

However, I'm not clear (even for the trivial example) why onion is public but Beta is private.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜