2

I'm having trouble with a JS prototype object I'm working on. What I'm trying to do is define a class-level variable as an object literal, then refer back to one of the class's prototype methods to set a property of the class-level variable, but I'm not getting anywhere. Here's what I am trying to do, in a simplified example:

var foo = function(args)
{
    this.name = 'bar';
}
foo.stuff = { barbaz: this.foobarbaz(2) };

foo.prototype.foobarbaz(int)
{
    return int;
}

alert(foo.stuff.barbaz); // should alert 2, but I'm missing something

I'm wondering if I'm just misunderstanding the scope of 'this' in this instance, or if this.foobarbaz() is undefined when I assign it to foo.stuff.barbaz.

Is it possible to refer to an object's prototype methods from within a class-level variable like this?

keithhamilton
  • 35
  • 1
  • 7
  • 1
    First, you should define your method on the prototype like `foo.prototype.foobarbaz = function(int) {...}`. Second, you're trying to use the method *before* you define it. Third, in this function you've provided, `this` is not `foo`. – apsillers Sep 13 '12 at 13:34
  • the omission of the function call on foo.prototype.foobarbaz was an error in writing the post - that is how I have it defined in my actual javascript file. so in the scope of `foo.stuff`, is `this` referring to `foo.stuff`? – keithhamilton Sep 13 '12 at 13:40
  • As I explain in my answer, `this` is always the same throughout the entirety of a single function; `this` does not change when you use it inside of an object literal. (However, it *may* change when used inside of a function definition, e.g., for a callback. As I also explain in my answer, a function's context (i.e. `this`) is set at function execution time and may vary depending on [how the function is invoked](http://stackoverflow.com/questions/12370851/understanding-javascript-scope-with-var-that-this/12371105#12371105).) – apsillers Sep 13 '12 at 13:49

1 Answers1

0

Here is what you need to know:

  1. You should define your method on the prototype like foo.prototype.foobarbaz = function(int) {...}. Your current syntax is not valid.

  2. You're trying to use the method before you define it. If you're expecting function hoisting to work here, that only applies to function declarations, not assignments. Move the assignment of foobarbaz above the first time you use it.

  3. In this function you've provided, this is not foo. Each function has its own value of this (called the function's "context"), set each time the function is invoked. You can see the rules for how a function's context is set in several answers to Understanding Javascript scope with "var that = this".

Instead, here, you'll need to use foo.foobarbaz(2) instead of this.foobarbaz(2), because this is probably window (assuming you call this code not as the method of an object and not in JavaScript's strict mode).

Community
  • 1
  • 1
apsillers
  • 101,930
  • 15
  • 206
  • 224