theHack
theHack

Reputation: 2014

javascript function structure

this is an exmaple.

var x=5;
var y=x.multiplied(6); // return y=30;

how to create a function like .multiplied() function on js?

the function structure is like this

var1.doSomething(var2);

Upvotes: 0

Views: 3345

Answers (3)

stecb
stecb

Reputation: 14746

If you want to create fn like multiplied, you need to extend the prototype of a particular type in the following case you need to extend a Native type i.e.

Number.prototype.multiplied = function(n){
    return this*n;
}

var x=5; //x is a Number
var y=x.multiplied(6); // return this*6 => this is x => that is 5 => 5*6 = 30;

in general, if you have var1.doSomething(var2); and var1 is an object, you could define 'methods' in this way

function myObject(name){
   if(!(this instanceof myObject)){ // in the case you're missing 'new' when you declare a myObject instance
       return new myObject(name); 
   }
   this.name = name; //field
   this.doSomething = function(param){ //method
        alert('done '+param+' '+this.name);
   }
}
var var1 = new myObject('peter');
var var2 = "string";
var1.doSomething(var2); //alerts "done string peter"

var var3 = myObject('jean'); //don't need 'new'
var var4 = "homework";
var3.doSomething(var4); //alerts "done homework jean"

var1 could also be a general 'library', and you could define it in this way:

var var1 = {
    doSomething : function(param){
       alert('done ' + param);
    }
}
//you don't need to instantiate a new object. You have a static library
var var2 = "mystring";
var1.doSomething(var2); //alerts "done mystring"

Upvotes: 1

at0mzk
at0mzk

Reputation: 1942

need to extend Number object like this..

var x = Number(5);
Number.prototype.multiplied = function(a) {return this * a;};

Upvotes: 1

SergeS
SergeS

Reputation: 11779


function myInteger( setVal ) {
 this.value = setVal;
}

myInteger.prototype.multiple( mult ) {
 return this.value * mult;
 // Or
 // return new myInteger( this.value * mult );
}

var x = new myInteger(5)
var y = x.multiple(6);

Upvotes: 2

Related Questions