0

I'd like to create a new object working like Date or Array in JavaScript, which can be called like a function Date(). Meanwhile, there are also other functions on it like Date.now() or Array.of(), which returns a new instance of this object.

How can I do that?

For example:

function Foo (lastName) {
    this.firstName = 'Foo'
    return this.firstName + ' ' + lastName
}

Foo('Bar') // 'Foo Bar'

Foo.setFirstName = function (firstName) {
    this.firstName = firstName
    /**
     * Here I want to return a new instance of Foo, with new firstName
     */
}

const foo = Foo.setFirstName('foo')

foo('bar') // 'foo bar'
Karl Bao
  • 401
  • 2
  • 4
  • 11
  • Check this article https://www.phpied.com/3-ways-to-define-a-javascript-class/ – Deepak Kumar T P Dec 26 '17 at 07:04
  • 2
    Possible duplicate of [How to "properly" create a custom object in JavaScript?](https://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript) – Rajesh Dec 26 '17 at 07:07

2 Answers2

0

function Foo (lastName) {
    this.firstName = 'Foo'
    return this.firstName + ' ' + lastName
}

Foo('Bar') // 'Foo Bar'
console.log(Foo('Bar') )

Foo.setFirstName = function (firstName) {
return function(lastName) {
   this.firstName = firstName;
   return this.firstName + ' ' + lastName
}
}

const foo = Foo.setFirstName('foo')

foo('bar') // 'foo bar'
console.log(foo('bar'));
zabusa
  • 2,520
  • 21
  • 25
  • I updated the question. Actually I want the new instance to have the same functions but different context with the original function. How can I do that? – Karl Bao Dec 26 '17 at 07:40
  • @KarlBao updated the answer to your need.it may help – zabusa Dec 26 '17 at 07:52
0

function Foo(lastName) {
  this.firstName = 'Foo'
  this.lastName = lastName;
  return this;
}

Foo('Bar') // {firstName:'Foo', lastName:'Bar'}

Foo.setFirstName = function(firstName) {
  let k = Object.assign({}, this);
  return Object.assign(k, {
    "firstName": firstName
  })
}

const foo = Foo.setFirstName('foo') //{firstName:'foo', lastName:'Bar'}

Object.assign will create new object as per first argument and append the properties from previous object, and we use Object.assign second time in order to override the properties as per our argument

Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73