【问题标题】:How can I declare a variable as a function as well as assign values to it [duplicate]如何将变量声明为函数并为其赋值[重复]
【发布时间】:2021-05-30 16:17:14
【问题描述】:

我试过了:

 var fun = function(){ console.log("booyah"} , {
  hell: function(){
    console.log("hello");
  },
  boy: ()=>{
    alert("blah");
  }
};
fun.boy();

我希望首先调用 fun 函数,然后调用我存储为对象的 Access 函数。但我收到错误。我该如何解决?或者有没有其他方法可以做到这一点? 请帮忙。

【问题讨论】:

  • 注意:当我调用 myObject.fun() 时,我想像函数一样工作,我可以访问存储在大括号内的函数作为对象,即首先它像函数一样,然后将一种 。我可以访问存储在其中的函数。有什么想法吗?

标签: javascript html function object


【解决方案1】:

你可以通过编辑函数原型来达到这种效果。

例子:

function foo() {
        const something = 'the thing';
    
        return something;
    }
    
    const customPrototype = {
        greeting: (name) => {
            const greetingTemplate = `Hello ${name}`;
    
            return greetingTemplate;
        },
    
        randomNumber: () => {
            return Math.random();
        },
    };
    
    // Extending prototype to access our custom prototype functions
    Object.assign(foo, customPrototype);
    
    
    console.log(foo()); // the thing
    console.log(foo.greeting('People')); // Hello People
    console.log(foo.randomNumber()); // 0.26138311987993545
    // Default prototype functions are working as well
    console.log(foo.toString()); // [object Function]

编辑:感谢@Bergi 纠正我!

【讨论】:

  • 你明白了兄弟?!!我被通缉了。您能否更新您的答案,以便我可以获取 foo 函数 foo(value) 的参数值,并且该函数仍然像 foo.greeting("Thank you bro for helping me") 一样工作
  • 您可以提供任意数量的变量并在您的函数中编写一些逻辑。如果您想添加更多功能,只需更新 customPrototype(在此处添加额外的属性/功能)。随意在那里写任何东西。
  • 不,不要使用已弃用的__proto__ 访问器!没有理由在这里摆弄原型(更糟糕的是,使foo 不再是instanceof Function)。只需写Object.assign(foo, customMethods) 即可。
  • @Bergi 我已经编辑了解决方案。感谢您的帮助!
【解决方案2】:

查看以下代码,参考取自Can you create functions with custom prototypes in JavaScript?

function MyFun() {
    if (!this || this==window) {
        return new MyFun();
    }

    var f = function() {
        return "thanks for calling!";
    }
    f.__proto__ = MyFun.prototype;
    f.constructor = MyFun;

    return f;
}

MyFun.prototype = {
    foo: function() {
        return "foo:" + this();
    },
    __proto__: Function.prototype
};

var f = new MyFun();
alert("proto method:"+f.foo()); // try our prototype methods
alert("function method:"+f.call()); // try standard function methods
alert("function call:"+f()); // try use as a function
alert('typeof:' + typeof f); // "function", not "object". No way around it in current js versions
alert('is MyFun:' + (f instanceof MyFun)); // true
alert('is Function:' + (f instanceof Function)); // true

【讨论】:

  • 但是我想像这样工作,当我调用 myObject.fun() 时,myObject 的作用类似于函数,我可以访问存储在花括号内的函数作为对象,即首先它的作用类似于函数并通过放置一个. 我可以访问存储在其中的函数。有什么想法吗?
  • 你为什么不把这个解释本身提出问题?
  • 对此我很抱歉?。我想我没有很好地解释我的问题。但我无法编辑问题,因为社区成员经常关闭我的问题。我是初学者,所以我需要时间。希望你能理解。
  • 更新了答案,我认为这个答案可能有助于解决您的问题。如果您觉得这有帮助,那么点个赞会让我开心。 :)
  • 我不能投票给你,因为我没有声誉:(但我可以标记为正确答案:)。
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多