考虑以下示例:
var FunctionName = () => {
return {
helloWorld() { console.log("hello world"); }
}
};
var OtherFunctionName = () => {
return {
goodBye() { console.log("Bye Bye"); }
}
};
假设我在上面没有做语法错误的事情,我如何在 OtherFunctionName
中扩展 FunctionName
以便 OtherFunctionName
能够访问helloWorld
??
因为代码库可能包含 ES6 类,是否可以使用相同的方法将所述类扩展为自包含函数以访问类方法?
所以:
var FunctionName = () => {
return {
helloWorld() { console.log("hello world"); }
}
};
class OtherClass {
goodBye() { console.log("Bye Bye"); }
};
在这种情况下,FunctionName
将扩展 OtherClass
以访问 goodBye
。 可能吗
有哪些方法可以在自包含函数上扩展自包含函数。
和
在自包含函数上扩展类的方法有哪些
这是 Object.assign 或 lodashes ._extend
派上用场的地方吗?
最佳答案
如果您想使用原型(prototype),可以使用Object.create
。
它允许您创建具有特定原型(prototype)的对象。
因为您不想将所有内容更改为“属性描述符”,所以可以将其与 Object.assign
结合使用:
var FunctionName = () => {
return Object.assign(Object.create(OtherClass.prototype), {
helloWorld() { console.log("hello world"); }
})
};
如果您想支持工厂函数和类,可以这样做:
var FunctionName = () => {
return Object.assign(
OtherClass.prototype ? Object.create(OtherClass.prototype) : OtherClass(), {
helloWorld() { console.log("hello world"); }
})
};
关于javascript - 扩展自容器功能 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37122330/