Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object_helper with functions properly in javascript

I am planning to create an object helper like this in my js:

var person_helper = {
   isAlive : function(person) {
      ...
   },
   isHisNameIs : function(person,name) {
      ...
   },
   isSeniorCitizen : function(person) {

   }
}

This way I am calling the helper like this:

person_helper.isAlive(person_object); 
person_helper.isHisNameIs(person_object,"Dan"); 
person_helper.isSeniorCitizen(person_object);

Now, My question is: since I am using the person object in the person helper and I will probably always use the same object over and over again - Is there a way to write the helper in a way that I can use it like this?:

person_helper(person_object).isAlive();
person_helper(person_object).isHisNameIs("Dan");
person_helper(person_object).isSeniorCitizen();
  1. Does it make any logic to write it this way? (mainly to avoid passing each time "person" object when defining the function)
  2. How do I write it so it will work?
like image 838
Alon Avatar asked Feb 12 '26 08:02

Alon


1 Answers

You must add a function into your helper and use the variable of parent function.

var person_helper = function(person) {
    var parent = this;
    this.name = person.name ;
    this.isHisNameIs = function(name) {
        if(name == parent.name)
            console.log('OK');
        else
            console.log('NOP');                    
    }
}

http://jsfiddle.net/H4RsJ/6/

like image 113
Genosite Avatar answered Feb 14 '26 23:02

Genosite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!