Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a method for a custom object in JavaScript?

Is it like...

var obj = new Object();  obj.function1 = function(){     //code } 

or something like that?

like image 801
MetaGuru Avatar asked Feb 02 '09 20:02

MetaGuru


People also ask

Can we define a method for the object in JavaScript?

JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition. Methods are functions stored as object properties.

What is the term for a JavaScript function used to create a custom object?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.


1 Answers

You can see from the answers that you have already that there is more than one way.

#1 var o = new Object(); o.method = function(){}  #2 var o = new Object(); o.prototype.method = function(){}  #3 function myObject() {     this.method = function(){} } var o = new myObject();  #4 function myObject() {} myObject.prototype.method = function(){} var o = new myObject();  #5 var o = {     method: function(){} } 

#3 and #4 are using a constructor function. this means you can use them to create a number of objects of the same 'class' (classes don't really exist in JavaScript)

#4 is different to #3 because all objects constructed with #4 will share an identical 'method' method because it is a property of their prototype. This saves memory (but only a very tiny amount) and if you change the method of the prototype, all #4 objects will immediately be updated - even if they've already been instantiated.

#1, #2 and #5 are all pretty much equivalent. This is because there will probably only ever be one of them at a time, so the fact that #2 has the method added to the prototype doesn't really matter. (not taking cloning into account)

There are still more ways of adding methods to objects using factories with closure or adding 'static' properties/methods to functions or private nested functions... :)

like image 52
meouw Avatar answered Sep 21 '22 12:09

meouw