如何在JS中使用构造函数创建对象?

时间:2017-12-26 07:02:40

标签: javascript

我想在JavaScript中创建一个像DateArray一样的新对象,可以像函数Date()一样调用它。同时,还有其他函数,如Date.now()Array.of(),它返回此对象的新实例。

我该怎么做?

例如:

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'

2 个答案:

答案 0 :(得分: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'));




答案 1 :(得分: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将根据第一个参数创建新对象,并附加上一个对象的属性,我们第二次使用Object.assign,以便根据我们的参数覆盖属性