0

I am trying to call a prototyped function from another javascript file but it doesn't seem to work.

BuddyList.js :

function BuddyList(){ .. }

BuddyList.prototype = {
    addBuddy : function(buddyName){...}
}

UserOptions.js:

function UserOptions(){
....
BuddyList.addBuddy(username);
}

I get an error stating that BuddyList does not have a method called addBuddy

3 Answers 3

1

You don't need to use the .prototype method. Since everything in JS is an object, you can simply extend BuddyList with a new function:

function BuddyList(){
     // do whatever
}

BuddyList.addBuddy = function(username){
      // do whatever
}
Sign up to request clarification or add additional context in comments.

Comments

0

.addBuddy is defined on objects that are constructed from the BuddyList constructor.

You can not call a method of an object like you are trying to do.

You might want to create it as a "static" function

BuddyList.addBuddy = function(buddyName) { ... }

You can then call it from the prototype aswell

BuddyList.prototype.addBuddy = function(buddyName) {
    BuddyList.addBuddy.apply(this, arguments)
}

You would need to check for any references to a BuddyList object inside the addBuddy function though.

Remember BuddyList is an object constructor. Calling the addBuddy method on the constructor doesn't make sense. I think you actaully want to do this

buddyList = new BuddyList;
buddyList.append(someBuddy);

In theory if there's only ever one BuddyList then you may want to look for

BuddyList = new BuddyList;

That will overwrite your constructor with an object inherited from the constructor.

You can always call the addBuddy method directly without an object through the prototype as follows:

BuddyList.prototype.addBudy.call(this, someBuddy)

It really depends on what your trying to do.

Comments

0

You can't access a prototype function until and unless you create an instance for the object or function. So instead of

BuddyList.addBuddy(buddyName) 

you have to write

new BuddyList().addBuddy(buddyName)

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.