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.

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. Commented Nov 5, 2013 at 1:30
  • var myObject = new MyClass(); works in javascript because of variable hoisting but MyClass.prototype.setAttribute is added where you think it would be Commented Nov 5, 2013 at 1:32
  • Thank you all, It worked well and I learned about hoisting. Commented Nov 5, 2013 at 1:39

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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');

Comments

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.