0

Say i have

function Person(birthDate){ // parameter accepting is unknown to the alias maker
    this.birthDate = birthDate;    
    this.getAge = function() {
      return new Date().getFullYear() - this.birthDate.getFullYear();
    };
};

i simply gave function name 'Person' to some-body, who does not know how many arguments Person can accept, and asked him to make alias of Person

That alias should work the same way as Person

var dave = new Alias_Person(new Date(1909, 1, 1)); // here number of parameters is unknown
dave.getAge(); //returns 100.

What should be alias?

Please note that, the alias should have its own function and not just the reference of Person

Currently i do,

var Alias_Person = function(){
    return Person.apply(null, arguments);
  };

But that doesn't return right result.

EDIT : my end aim is to get rid of 'new' to be used with Date. simply using Date() always result into current date and time. I want something like this

My_Date({parameters}) to return the same result as that with 'new Date({parameters})'

codeofnode
  • 18,169
  • 29
  • 85
  • 142

1 Answers1

3

You can simply do var Alias_Person = Person.

If you really need to use a different function for some reason, you'll need to re-assign the prototype so that both constructors use the same object for inheritance.

function Alias_Person() {
    return Person.apply(this, arguments);
//                      ^^^^ also don't forget to pass the instance
}
Alias_Person.prototype = Person.prototype;

If you don't care about Alias_Person being called with new or not and just want to return a Person instance, have a look at Use of .apply() with 'new' operator. Is this possible?, which might lead to something like

function Alias_Person() {
    var inst = Object.create(Person.prototype);
    return Person.apply(inst, arguments) || inst;
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • But i dont know prototype of base Function.. oh now looking into edit – codeofnode Feb 27 '15 at 13:10
  • well my end aim to use Date with new operator – codeofnode Feb 27 '15 at 13:28
  • If i don't use new with Date it give always the current date, I just want to get rid of 'new' – codeofnode Feb 27 '15 at 13:29
  • the solution doesn;t worked yet, using : function My_Date(){ var inst = Object.create(Date.prototype); return Date.apply(inst, arguments); } is returning the same result as of Date – codeofnode Feb 27 '15 at 13:38
  • Aww, these techniques [will not work with the built-in `Date` constructor](http://stackoverflow.com/a/11408806/1048572). If you're looking to fake dates, have a look [here](http://stackoverflow.com/a/21591320/1048572) – Bergi Feb 27 '15 at 13:38