I have an object of functions and I like to prototype another function to all of these properties.
Example:
var test = function(num) {
return num * num / (num/4);
}
var obj = {
item1: item1, //this is a function already setted.
item2: item2, //this is a function already setted.
item3: item3 //this is a function already setted
}
What I want is something like: obj.item1().test()
without setting this.test
inside each function.
Your test
function
return num * num / (num/4);
is exactly equivalent to num * 4
as far as I can see.
Anyway, the example itemX
given in your comment returns a number. The only way to be able to call the function test
on a number is to add it to the Number
prototype, which some people would say is a bad idea:
Object.defineProperty(Number.prototype, 'test', { value: function () {
return this * this / (this/4);
});
If you want to be able to chain test
from the result of the call to obj.itemX
, then the latter needs to return this
, not this.num
:
var itemX = function(val) {this.num = val; return this};
Now you just need to place a modified version of test
once on obj
:
var obj = {
item1: item1, //this is a function already set.
item2: item2, //this is a function already set.
item3: item3, //this is a function already set.
test: function() { return test(this.num); }
};
> obj.item1(22).test()
< 88
How can I make a prototype function to all my object properties?
If you are referring to test
, this is not a prototype function. It's just a plain old method on an object. To add it, just add it on the object, as done above.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments