0

I'm a begginer at Javascript and programming in general, my english is not good(sorry if there's any grammar error) but this is my problem:

When I create a class in JS and I create a function to set an attribute of its objects, the browser does not recognise the function. example:

var myObject = new MyClass();
myObject.setAttribute();

function MyClass() {
    this.attribute;
}

MyClass.prototype.setAttribute = function() {
    this.attribute = true;
};

When I try to run this code chrome throws an error saying "Uncaught TypeError: Object # has no method 'setAtributte' " and the specified line is 2. I don't get it.

I repeat: i'm a begginer so this may look like a silly error to you, but it's quite a big problem for me. thanks.

Dovail
  • 3
  • 3
  • 7
    You're calling ".setAttribute()" before you've actually defined it. If you move that line of code to after the point at which you add the function to the prototype, it'll work. Code is evaluated line by line. – Pointy Nov 05 '13 at 01:30
  • `var myObject = new MyClass();` works in javascript because of [variable hoisting](http://stackoverflow.com/questions/3725546/variable-hoisting) but `MyClass.prototype.setAttribute` is added where you think it would be – megawac Nov 05 '13 at 01:32
  • Thank you all, It worked well and I learned about hoisting. – Dovail Nov 05 '13 at 01:39

2 Answers2

2

JavaScript has 'hoisted' your declarations so that MyClass is defined before your variable declaration; however your prototype update is not hoisted. Change the order of your code

function MyClass() {
    this.attribute;
}

// Prototype has to be defined BEFORE it can be used
MyClass.prototype.setAttribute = function() {
    this.attribute = true;
    console.log(this.attribute);
};

var myObject = new MyClass();
myObject.setAttribute();
jasonscript
  • 6,039
  • 3
  • 28
  • 43
0

Functions declared with the function name() {} syntax gets hoisted at the top which allows you to call the function before it's defined in the code, however that doesn't hold true for every other lines.

Your code is basically evaluated as:

var MyClass = function MyClass() {
    this.attribute;
}

var myObject = new MyClass();

myObject.setAttribute(); //does not exist since it's defined on the line below

MyClass.prototype.setAttribute = function() {
    this.attribute = true;
};

You should just reorder your code as:

//constructor declaration
//setting prototype values

var myObject = new MyClass();
myObject.setAttribute('test');
plalx
  • 42,889
  • 6
  • 74
  • 90