【发布时间】:2016-04-06 18:09:40
【问题描述】:
假设我们有两个库:
某人编写的库,使用
function和prototype语法在JS中构建类类类型。我们使用 ES6 编写的库,扩展了第一个库。
使用class OurLibrary extends TheOtherLibrary {...} 可以正常工作(即使TheOtherLibrary 是使用function TheOtherLibrary (...) {...} 声明的,并且它的方法是使用prototype 方式附加的)。
问题是在不使用类的时候,可以return 取值。一种常见的方法是在没有new 的情况下处理呼叫。这就是我现在遇到的问题。
我们有这样的东西:
function TheOtherLibrary (foo) {
if (this.constructor !== TheOtherLibrary) {
return new TheOtherLibrary(foo);
}
//...
}
TheOtherLibrary.someMethod = function () {/*...*/};
class MyLibrary extends TheOtherLibrary {
constructor (foo) {
super(foo);
}
anotherMethod () {/*...*/}
}
var bar = new MyLibrary(42);
console.log(bar.constructor.name);
// => TheOtherLibrary
console.log(bar.anotherMethod);
// => undefined
那么,如何改进第二行中的 if 表达式以检查调用是否来自扩展类?
var notCalledFromExtendedClass = ???
if (this.constructor !== TheOtherLibrary && !notCalledFromExtendedClass) {
return new TheOtherLibrary(foo);
}
或者是否有希望以另一种更好的方式实现这一点?
【问题讨论】:
标签: javascript class prototype