0

Why is this undefined:

var testObj = {
   CONSTANT: "blah",
   someVal: this.CONSTANT
}
console.debug(testObj.someVal); // prints "undefined"

If it has to do with the fact that I am actually creating a new prototype and therefore the this keyword is not working, then I'd also like to know the following:

I am using Dean Edward's base.js and I am trying to do something similar to the above: I have an object that extends Base:

Test = Base.extend({
  testObj: {
   someVal: this.CONSTANT
  }
  CONSTANT: "blah";
});
var test1 = new Test();
console.debug(test1.testObj); // someVal is undefined

In the above, if I do someVal: "blah" this it works as expected; I'm just not sure why I can't access this.CONSTANT. If its because this is applied to the scope of testObj and not Test, then how do I solve this (I tried setting a that: this variable, with no luck)?

Update: based on the answers I see that I am doing this wrong. My question now is: using the base.js model, is there a way to have "class-level" constants that are accessible from within the same class (outside of functions)?

2 Answers 2

5

this references the window not the object.

var CONSTANT =  "blah";
var testObj = {
   someVal: this.CONSTANT
}
testObj.someVal; // blah

You can't access the object itself with object notation.


You a function to change the scope of this:

function testObjCreator() {
  this.CONSTANT = "blah";
  return ({
      val: this.CONSTANT
  })
}
var a = new testObjCreator()
a.val; // blah
Sign up to request clarification or add additional context in comments.

5 Comments

good point: what about the 2nd case (which is what I'm really interested in). looking at the base.js (the Animal class example) Dean uses "this" to access the object itself. thanks.
in the base.js example I gave, it definitely seems like a scope issue to me ("this" is not referencing the right scope)..I just don't know how to fix that.
In the second example, this is still the window
is there a way to access the CONSTANT?
I've added an update to show how you could change the scope of this
0

"this" is (locally) defined only within a function which has been called as a method.

base.js uses "this" only within a function definition, where it designates the object on which the function was called as a method. Your examples don't contain any function definitions.

1 Comment

good point; is there a way to do what I am trying to do? basically having class level constants that I can access within the same class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.