bladekp
bladekp

Reputation: 1657

JS TypeError: is not a function

I have situation as follows

function Field(data){
    var name = data.name;
    this.foo = function(){
        console.log("foo");    
    }
}
...
field = new Field(someData);
...
console.log(field.name); //returns its name as expected
field.foo(); //TypeError: field.foo is not a function

What's problem with that? I use it in angularjs application.

Im backend developer so please be understanding.

Upvotes: 4

Views: 3884

Answers (1)

Nathan Friend
Nathan Friend

Reputation: 12834

You will need to assign name to the current context (this). However, the foo() function should be working as you have it in your question. See this code snippet as a demonstration:

function Field(data) {
  this.name = data.name;
  this.foo = function() {
    document.writeln('foo' + '<br />');
  }
}

var someData = { name: 'MyName' };
var field = new Field(someData);
document.writeln(field.name + '<br />');
field.foo();

Upvotes: 1

Related Questions