如何将变量声明为函数并为其赋值?



我试过了:

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

我想首先调用fun函数,然后调用作为对象存储的Access函数。但是我得到了错误。我该怎么修理它?或者还有其他方法吗?请帮助。

您可以通过编辑函数的原型来实现这种结果。

的例子:

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纠正我!

检查下面的代码,参考取自您可以在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

最新更新