0

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

3 Answers 3

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

3 Comments

do i have to specify the variable like this ar x = new myInteger(5)? can't i just specify var=5; like another js function?...
if you specify it like var foo = 5; it will use built-in type integer( and AFAIK there is no way to bind function to integer ) - so only solution is to create own prototypes - objects, made exactly by your needs
you CAN extend built-in types through their prototypes.. i.e. Number.prototype.foo = function(){} or String.prototype.trim = function(){ ... }
1

need to extend Number object like this..

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

Comments

1

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"

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.