Creando un object_helper con funciones correctamente en 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 persona objeto en el 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?

preguntado el 28 de agosto de 12 a las 10:08

Why not adding these methods to the person class ? -

5 Respuestas

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/

Respondido 28 ago 12, 11:08

In my opinion it is not such a good idea to create a person_helper. Instead you should create a Person prototype, read este para obtener más información.

You should have members such as Name and Alive and you can implement your functions based on your requirements.

Respondido 28 ago 12, 10:08

I agree with others saying those methods should be part of the person object. It would make more sense I think.

But for the fun of it, what you want is something similar than what underscore.js offers. All methods can be called in a functional way, but you can also wrap an object / array to call those methods in an object oriented way.

For that to work, you have to define person_helper as a function, assign these methods to its prototype and to itself as static methods:

var person_helper = (function() {

    var methods = {
       isAlive : function(person) {},
       isHisNameIs : function(person,name) {},
       isSeniorCitizen : function(person) {}
    };

   var Helper = function(person) {
       if(!(this instanceof Helper)) { // so we can call the function with `new`
           return new Helper(person);    
       }
       this.person = person;
   };

   // set up instance and static methods
   for(var m in methods) {
       (function(m) { // instance methods setup
            Helper.prototype[m] = function() {
                 // call the original method, passing `this.person` as
                 // first argument
                 return methods[m].apply(null, [this.person].concat(arguments));
            };
        }(m));

       Helper[m] = methods[m]; // static method
   }

   return Helper;
}());

Entonces puedes usarlo como:

person_helper.isHisName(person, 'Dan');
person_helper(person).isHisName('Dan');

DEMO

Respondido 28 ago 12, 11:08

You will find very good stuff about that on the W3Schools.com website, Javascript Object Section. The point is you can create an Object you will store as a property of your person_helper:

var person_helper = {
    ...
    /** which is the same than create a new instance of Person Object. */
    person : function person(firstname,lastname,age,eyecolor) {
        this.person = {};
        this.person.firstname=firstname;
        this.person.lastname=lastname;
        this.person.age=age;
        this.person.eyecolor=eyecolor;
    },
    ...
};

And you will retrieve personinside your helper properties. The downside is you have to manage the person object foreach person_helper. But it is not a big problem.

Respondido 28 ago 12, 11:08

You still might want to go to tontos and learn why w3schools is not the best reference you want to use. - Yoshi

Of course, using prototype is the best way to go for these king of stuff. But sometimes people don't want a headache to do the simplest things, and don't want to add dependencies to their apps because of lack of knowledge or timeless fool hurry. - BendaThierry.com

I can quote selfhtml.org if you will prefer. Didn't expect that i've just read about w3schools on the website you have given. - BendaThierry.com

Continuing your example using Object.create ():

var person_helper = function(newp) {
   return Object.create({
       person : newp,
       isAlive : function() {
           println(this.person + " is alive");
       },
       isHisNameIs : function(name) {
           println(this.person + " name is " + name);
       },
       isSeniorCitizen : function() {
           println(this.person + " is getting on in age..");
       }});
};

var person_object = "some guy";

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

Ejecutando esto con el jdk8 versión de jrunscript huellas dactilares:

some guy is alive 
some guy name is Dan
some guy is getting on in age..

You also have the option of treating the result of person_helper() as an object to avoid re-construction:

var personObj = person_helper(person_object);
personObj.isAlive();    
personObj.isHisNameIs("Dan"); 
personObj.isSeniorCitizen();

Respondido 28 ago 12, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.