繁体   English   中英

返回函数或对象Javascript

[英]Return Function or Object Javascript

我的代码已经可以工作了,但是我想问一下是否有任何更改可以使我的函数声明为对象,而不是没有提供任何参数?

这是我的mixin函数如下:

import Page from "@/models/Page.js";

/**
 * @param  {number} pageId id in page table
 */
export default function (pageId) {
  return {
    data() {
      return {
        page: Page
      }
    },
    created() {
      this.initPageContents();
    },
    methods: {
      async initPageContents() {
        if (pageId) {
          await Page.addPage(pageId);
        }
      }
    }
  }
}

我叫它

  mixins: [
    pageMixin(24),
  ],

要么

  mixins: [
    pageMixin(),
  ],

现在再问我一个问题。 是否可以将其称为也像没有参数的函数一样工作的对象?

  mixins: [
    pageMixin,
  ],

不,您不能-该数组中的内容是一个函数引用,这意味着您只能这样做:

mixins[0]()

调用您的函数。 如果要将函数的返回值存储在数组中,则需要做已经在做的事情:

mixins: [
  pageMixin()
]

我不是Java语言专家,但是我把我认为是解决方案的问题凑在一起。 它基于此SO问题

我将您的问题简化为:“我有一个函数f 。我想要一个对象o以便o行为类似于f() ,而o(a, b, c, ...)行为类似于f(a, b, c, ...)

举例来说,我们有一个用于创建“人物”的功能:

function makePerson(firstname, age) {
  firstname = firstname || "Jackson";
  age = age || 17;
  return { firstname: firstname, age: age };
}

我们希望makePersonmakePerson() 我认为让makePerson.firstname == "Jackson"makePerson.age == 17就足够了。 也就是说,我们关心使所有属性正确。

我们可以通过将makePerson的原型设置为具有所需属性的新函数对象来实现:

// Create a function object
const functionObject = Object.create(Function.prototype);
// Get the default value
const defaultValue = makePerson();
// Copy all the attributes from the default value to the function object
Object.assign(functionObject, defaultValue);
// Make the function object the prototype of our function
Object.setPrototypeOf(makePerson, functionObject);

并看到这可行:

console.log(makePerson.firstname); // Jackson
console.log(makePerson.age); // 17

// Still works as a function
console.log(makePerson()); // { name: 'Jackson', age: 17 }
console.log(makePerson("Oliver", 50)); // { name: 'Oliver', age: 50 }

如果需要,可以将其全部包装在一个函数中:

function emulateDefault(func) {
  /* Return a function `newFunc` such that `newFunc` behaves like
     `func()` and `newFunc(...args)` behaves like `func(...args)`. */

  // Clone `func`
  const funcClone = Object.create(Function.prototype);
  Object.assign(funcClone, func);

  // Create a function object
  const functionObject = Object.create(Function.prototype);
  // Get the default value
  const defaultValue = func();
  // Copy all the attributes from the default value to the function object
  Object.assign(functionObject, defaultValue);
  // Make the function object the prototype of our function
  Object.setPrototypeOf(funcClone, functionObject);

  return funcClone;
}

然后您可以像这样写pageMixin

const pageMixin = emulateDefault(function() { ... });

我想指出的是,我对这里所发生的一切都不是100%积极,并且可能有些我没有考虑的极端情况。 特别地, JavaScript克隆特别困难 ,因此emulateDefault可能会因此而出现问题,并且我不知道Object.newObject.setPrototypeOfObject.assign的详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM