Yann Moisan
Yann Moisan

Reputation: 8281

TypeError when I use this in an object

Can you explain why this code returns this error TypeError: this.b is not a function:

var a = {
  b: function() {
    return 1;
  },
  c: this.b()
}

Upvotes: 1

Views: 84

Answers (2)

Quadrivium
Quadrivium

Reputation: 137

Try this:

var maker = function(){  
    this.b = function(){return 1;};
    this.c = b();
}

var a = new maker();

console.log(a.b());
console.log(a.b);
console.log(a.c);

the keyword 'new' is the key.

You can create functions that just get called, without using 'new'

or a functions that will create and return a new object and using new is needed, these are typically referred to as constructor functions, but the key thing is the use of keyword new here which changes the behavior of the function, notice that there is no 'return this;' line in the function, it's implied by using 'new'

hope that helps. When that makes sense, look at the prototype process a bit deeper and play with it.

Upvotes: 0

rajuGT
rajuGT

Reputation: 6404

Because during object a initialization, the this is pointing to window object, only in constructor function this will be in the context of the new object getting created.

Try this for more info.

var a = {b: function() {return 1;}, c: this}
console.log(a.c) //output is window object

Upvotes: 4

Related Questions