开发者

calling prototyped function in javascript without creating an object

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开发者_C百科 : function(buddyName){...}
}

UserOptions.js:

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

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


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
}


.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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜